Get distinct list values

后端 未结 8 860
余生分开走
余生分开走 2020-12-17 17:58

i have a C# application in which i\'d like to get from a List of Project objects , another List which contains distinct objects.

i trie

8条回答
  •  失恋的感觉
    2020-12-17 18:30

    You need to define "identical" here. I'm guessing you mean "have the same contents", but that is not the default definition for classes: the default definition is "are the same instance".

    If you want "identical" to mean "have the same contents", you have two options:

    • write a custom comparer (IEqualityComparer) and supply that as a parameter to Distinct
    • override Equals and GetHashCode on Project

    There are also custom methods like DistinctBy that are available lots of places, which is useful if identity can be determined by a single property (Id, typically) - not in the BCL, though. But for example:

    if (model != null) model = model.DistinctBy(x => x.Id).ToList();
    

    With, for example:

    public static IEnumerable
        DistinctBy(this IEnumerable items,
        Func selector)
    {
        var uniques = new HashSet();
        foreach(var item in items)
        {
            if(uniques.Add(selector(item))) yield return item;
        }
    }
    

提交回复
热议问题