LINQ加入了不同的结果集 [英] LINQ join with distinct resultset

查看:54
本文介绍了LINQ加入了不同的结果集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ问题.我对linq不太满意.我有两节课:

I have a LINQ question. I am not great with 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;}

我想编写一个LINQ查询,该查询将为所有"Person"类返回不同的状态列表. sql中的一个例子是

I would like to write a LINQ query that would return a distinct 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.

推荐答案

Linq令人讨厌,您必须在要Distinct()的类上实现IEqualityComparer接口,然后才能获得与众不同的选择指的是:

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:

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

SelectMany()使结合可枚举的结果变平,因此您不会得到IEnumerable< IEnumerable< State>.但得到IEnumerable< State>

SelectMany() flattens the result unioning the enumerables so you don't get IEnumerable<IEnumerable<State>> but get IEnumerable<State>

在实现IEqualityComparer时,知道Distinct()确实验证了Equals()的结果是否相等,而GetHashCode()的结果是否相等.我认为在您的情况下,您想在State类上实现比较器.

When implementing the IEqualityComparer know that Distinct() does validate both the results from Equals() are equivalent, and the results from GetHashCode() are equivalent. I think in your case you want to implement the comparer on the State class.

可能看起来像这样:

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; }
}

请记住,如果您未实现IEqualityComparer,那么您的distinct()不会为您做任何事情.

Remember, your distinct() will do nothing for you if you don't implement the IEqualityComparer.

这篇关于LINQ加入了不同的结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆