I’ve been using LINQ for a while now, but seem to be stuck on something with regards to Unique items, I have the folling list:
List<Stock> stock = new List<Stock>();
This has the following Properties: string ID , string Type, string Description, example:
public class Stock
{
public string ID { get; set; }
public string Type { get; set; }
public string Description { get; set; }
}
I want to have a LINQ query that will group the items in Stock by their Type and return this as a new List of Stock (it has to be the same type as the original Stock List).
Example Data:
ID Type Description
----------------------------------------------
1 Kitchen Appliance Dishwasher
2 Living Room Television
3 Kitchen Appliance Washing Machine
4 Kitchen Appliance Fridge
…
My Linq query wants to be able to return all the Kitchen Appliances for Example.
So I would pass this as a “type” into the query and it would return the items 1, 3 and 4
from this example list.
This list returned must also be of type: List<Stock>.
Essentially I want a list of the unique items by type, kind of like an SQL Distinct query, how do I achieve this in LINQ?
Alternative solutions are fine but must be Silverlight / C# client code only.
Just another clarification is that I also may not provide the parameter “Kitchen Appliance” and may just want the unique ones, for example It would return Kitchen Appliance and Living Room once each only to kind of like a category no matter how many of that Type there are.
Flexible approach
Use
GroupByandToDictionaryto create a dictionary ofList<Stock>values keyed on theTypeproperty:Then you can access the types themselves as well as a list for any given type quite easily:
This approach really takes care of all your needs, as I see it. But for some other options, see below.
Alternate (quick & dirty) approach
You can always just use
Whereto get the items of the type you want, thenToListto put these items in a newList<Stock>:In response to this last part:
Here, you seem to be wanting something completely different: basically the behavior provided by
Distinct. For this functionality, you could essentially go with Soonts’s answer (optionally, returning anIEnumerable<tKey>instead ofIEnumerable<tSource>), or you could just leverageDistinctin combination withSelectto avoid the need to implement anIEqualityComparer<Stock>(see below).Update
In response to your clarification, here’s my recommendation: two methods, one for each purpose (Single Responsibility Principle):