linq query to return distinct field values from a list of objects

前端 未结 7 1828
醉梦人生
醉梦人生 2020-12-24 11:42
class obj
{
    int typeId; //10 types  0-9 
    string uniqueString; //this is unique
}

Assume there is list with 100 elements of obj, but only 10

7条回答
  •  醉酒成梦
    2020-12-24 11:44

    If just want to user pure Linq, you can use groupby:

    List distinct =
      objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();
    

    If you want a method to be used all across the app, similar to what MoreLinq does:

    public static IEnumerable DistinctBy
        (this IEnumerable source, Func keySelector)
    {
        HashSet seenKeys = new HashSet();
        foreach (TSource element in source)
        {
            if (!seenKeys.Contains(keySelector(element)))
            {
                seenKeys.Add(keySelector(element));
                yield return element;
            }
        }
    }
    

    Using this method to find the distinct values using just the Id property, you could use:

    var query = objs.DistinctBy(p => p.TypeId);
    

    you can use multiple properties:

    var query = objs.DistinctBy(p => new { p.TypeId, p.Name });
    

提交回复
热议问题