Remove duplicates from a List in C#

前端 未结 27 1844
广开言路
广开言路 2020-11-22 04:41

Anyone have a quick method for de-duplicating a generic List in C#?

27条回答
  •  青春惊慌失措
    2020-11-22 05:31

    I like to use this command:

    List myStoreList = Service.GetStoreListbyProvince(provinceId)
                                                     .GroupBy(s => s.City)
                                                     .Select(grp => grp.FirstOrDefault())
                                                     .OrderBy(s => s.City)
                                                     .ToList();
    

    I have these fields in my list: Id, StoreName, City, PostalCode I wanted to show list of cities in a dropdown which has duplicate values. solution: Group by city then pick the first one for the list.

    I hope it helps :)

提交回复
热议问题