LINQ Combines with Excellent Results

I have a LINQ question. I do not really like linq. I have two classes:

[Person] string FirstName {get;set;} string LastName {get;set;} IEnumerable<State> LastName {get;set;} [State] int StateID {get;set;} string StateName {get;set;} 

I would like to write a LINQ query that will return a separate list of states for all Person classes. An example in sql would be

 SELECT DISTINCT s.StateID FROM Person p JOIN States s ON (p.StateID = s.StateID) 

Any help on this would be greatly appreciated.

+4
source share
3 answers

The Linq cell is annoying, you need to implement the IEqualityComparer interface in the class you want to distinguish (), then the way you get your highlighted selection that you have in mind will be:

 IEnumerable<Person> people = GetPeople(); people.SelectMany((person) => person.LastName).Distinct(); 

SelectMany () aligns the result of combining the enumerated elements, so you don't get IEnumerable <IEnumerable <State → gt; but get IEnumerable <State>

When implementing IEqualityComparer, it is known that Distinct () checks both results from Equals () are equivalent, and the results from GetHashCode () are equivalent. I think in your case you want to implement a comparator in the State class.

It might look something like this:

 public class State : IEqualityComparer<State> { int StateID {get;set;} string StateName {get;set;} public bool Equals(State x, State y) { return x.StateID == y.StateID && x.StateName == y.StateName; } public int GetHashCode(State obj) { return obj.StateId; } } 

Remember that your separate () will not do anything for you if you do not implement IEqualityComparer.

+5
source

Try the following:

 var stateList = (from s in context.States join p in context.Persons on s.StateId equals p.StateId select s).Distinct(); 
+2
source

Like this:

 people.SelectMany(p => p.States).Distinct(); 

Note that you need to correctly implement Equals and GetHashCode in the State class. (If you are not using LINQ-to-SQL or entities)

If you just need identifiers, you do not need to implement Equals / GetHashCode ; you can just call

 people.SelectMany(p => p.States).Select(s => s.StateId).Distinct(); 
+1
source

All Articles