Reputation: 129
Given the following simple property
Class Data
{
public string AA { get; set; }
public int BB { get; set; }
public int CC { get; set; }
...
}
and a List of data items
List<Data> Items = new List<Data>;
which has some example data
"2002", 3 ,5 ..
"2002", 3 ,5 ..
"2006", 4 ,2 ..
"2002", 3 ,5 ..
"2018", 9 ,7 ..
"2018", 5 ,5 ..
I need to find the distint values of string AA, so I can use the following code
foreach(var itm = Items.Select(x => x.AA).Distinct()))
{
use itm ...
}
which corectly returns itm = string "2002", "2006" and "2018", However I also need to recover some remaining properties i.e. BB etc for the "Distinctly Selected" item, which will also be distinctly relevant to the primary field.
I have tried manys ways to try to achieve this but have been unsuccessful and so would be grateful if someone could indicate a way how to achieve this.
I have tried to recovey an index to the item, return the base item i.e. Data which work as far in returning all items in the list.
In practise there are many tens of thousands of data items and I need to recover fields linked to the distint data item.
I currently have a working solution where I extract the distinct items then use the generated list to search for the first matching item, then recover the data. It works but its not very elagant as I have to process extra times against the list.
Note there is no SQL options in this solution, supplied data is XML or JSON solution has to be standalone exe
comments welcome
Thanks
Upvotes: 0
Views: 76
Reputation: 1837
Create another variable and apply group by on that variable it should be work.
var another_item = Items.GroupBy(x => x.AA).ToList();
foreach(var itm in another_item)
{
use itm ...
}
Upvotes: 0
Reputation: 32296
Distinct is just a group by without any aggregation. What you want is to group on AA
and then aggregate the values, specifically you want to take the first match, which can be done like this.
Items.GroupBy(x => x.AA, x => x, (x,grp) => grp.First())
Upvotes: 1