简体   繁体   English

LINQ以不同的结果集连接

[英]LINQ join with distinct resultset

I have a LINQ question. 我有一个LINQ问题。 I am not great with linq. 我对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 would return a distinct list of states for all "Person" classes. 我想编写一个LINQ查询,它将返回所有“Person”类的不同状态列表。 An example in sql would be sql中的一个例子是

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

Any help on this would be greatly appreciated. 任何有关这方面的帮助将不胜感激。

Try this: 尝试这个:

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

Linq distinct is annoying, you have to implement the IEqualityComparer interface on the class you want to Distinct(), then the way you get your distinct selection you're referring to would be: Linq distinct很烦人,你必须在你想要Distinct()的类上实现IEqualityComparer接口,那么你得到你所指的不同选择的方式是:

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

SelectMany() flattens the result unioning the enumerables so you don't get IEnumerable<IEnumerable<State>> but get IEnumerable<State> SelectMany()将结果与可枚举结合起来,这样你就不会得到IEnumerable <IEnumerable <State >>但得到IEnumerable <State>

When implementing the IEqualityComparer know that Distinct() does validate both the results from Equals() are equivalent, and the results from GetHashCode() are equivalent. 实现IEqualityComparer时,知道Distinct()确实验证了Equals()的结果是等效的,GetHashCode()的结果是等效的。 I think in your case you want to implement the comparer on the State class. 我认为在你的情况下你想在State类上实现comparer。

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, your distinct() will do nothing for you if you don't implement the IEqualityComparer. 请记住,如果不实现IEqualityComparer,则您的distinct()将不会为您执行任何操作。

Like this: 像这样:

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

Note that you will need to correctly implement Equals and GetHashCode in the State class. 请注意,您需要在State类中正确实现Equals GetHashCode (Unless you're using LINQ-to-SQL or entities) (除非您使用的是LINQ-to-SQL或实体)

If you just want the IDs, you don't need to implement Equals / GetHashCode ; 如果您只想要ID,则不需要实现Equals / GetHashCode ; you can simply call 你可以简单地打电话

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM