简体   繁体   中英

Recover a list item, from a list item distinct property

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 ie 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 ie 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

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())

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 ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM