Is linq different?

I wonder how can I achieve this?

I want to get only different names from the collection of objects

MyObject a = new Object(); a.Name = 'One'; a.Value = '10'; MyObject b = new Object(); b.Name = 'One'; b.Value = '15'; MyObject c = new Object(); c.Name = 'Two'; c.Value = '10'; 

So, I want to return only the name. I'm not interested in the meaning in this case, just the name.

So i tried

// add all objects to the collection.

 myCollection.Disinct()..Select(x => new MyClassToStore() {Text = x.Name, Value = x.Name}).ToList()); 

However, I need to make a distinction at the property level not at the object level. Therefore, I want to return "One" and "Two." Right now I'm getting One, One, and Two back.

I see a library called morelinq , but I'm not sure if I will use it since it is still in beta and does not seem to be developed for more.

Plus an entire library for a single retrieval request. I'm not sure if it’s worth it.

+6
source share
5 answers

This fills in the Text and Value fields:

  myCollection.Select(x => x.Name).Distinct() .Select(x => new MyClassToStore { Text = x, Value = x }).ToList(); 
+14
source

Maybe something like this can help?

 var distinctItems = items .GroupBy(x => x.PropertyToCompare) .Select(x => x.First()); 
+22
source

If you just need to return different names, you can use:

 myCollection.Select(x => x.Name).Distinct().ToList(); 
+6
source

Personally, I suggest you redefine the == and! = Operator and determine how and why the object is unique there. Then use the Distinct () call in the collection.

You need to be careful with null values, see Microsoft Recommendations for Overloading Equals () and Operator == (C # Programming Guide) .

+2
source

You can implement your class so that the linq operator is different by default.

 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(); } } 
+2
source

Source: https://habr.com/ru/post/885580/


All Articles