Distinct in linq?

前端 未结 5 1265
我寻月下人不归
我寻月下人不归 2020-12-31 20:07

I am wondering how can I achieve this?

I want to get only distinct names from a collection of objects

MyObject a = new Object();
a.Name = \'One\';
a.         


        
相关标签:
5条回答
  • 2020-12-31 20:19

    Maybe something like this can help?

    var distinctItems = items
         .GroupBy(x => x.PropertyToCompare)
         .Select(x => x.First());
    
    0 讨论(0)
  • 2020-12-31 20:19

    If you just want back distinct names, you can use:

    myCollection.Select(x => x.Name).Distinct().ToList();
    
    0 讨论(0)
  • 2020-12-31 20:24

    You can implement your class so the linq distinct operator does not use the default equality comparer.

    class YourClass:IEquatable<YourClass> 
    {
    

    ... Your implementation details. ...

        public bool Equals(YourClass other)
        {
            if (Object.Equals(this, other))
            {
                return true;
            }
            else
            {
                if(Name == other.Name && Value == other.Value)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    
     public override int GetHashCode()
     {
         return Name.GetHashCode() ^ Value.GetHashCode();
     }
    
    }
    
    0 讨论(0)
  • 2020-12-31 20:29

    This populates both the Text and Value fields:

       myCollection.Select(x => x.Name).Distinct()
          .Select(x => new MyClassToStore { Text = x, Value = x }).ToList();
    
    0 讨论(0)
  • 2020-12-31 20:34

    Personally I suggest you override operator == and != and determine how and why an object is unique there. Then use the Distinct() call on the collection.

    You do have to be careful with null values, see Microsoft's Guidelines for Overloading Equals() and Operator == (C# Programming Guide).

    0 讨论(0)
提交回复
热议问题