LINQ连接查询并返回不重复的结果集

9
我有一个 LINQ 的问题。我不太擅长 LINQ。我有两个类:
[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示例如下:
SELECT DISTINCT s.StateID
FROM Person p
JOIN States s ON (p.StateID = s.StateID)

任何关于此事的帮助将不胜感激。
3个回答

13

试试这个:

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

5

Linq的去重操作(distinct)有点麻烦,你需要在要进行Distinct()操作的类上实现IEqualityComparer接口。然后你可以按以下方式获取你想要的去重结果:

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

SelectMany()方法将可枚举对象联合并展开,因此您不会得到IEnumerable<IEnumerable<State>>,而是得到IEnumerable<State>

实现IEqualityComparer接口时,请注意Distinct()方法会验证Equals()方法和GetHashCode()方法的结果是否相等。我认为在您的情况下,您需要在State类上实现比较器。

可能看起来像这样:

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()对你来说是无效的。

感谢您的回复,正如您已经提到的那样,关键是创建自己的实现。 - TheWebGuy

2

就像这样:

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

请注意,在State类中,您需要正确实现EqualsGetHashCode。(除非您使用LINQ-to-SQL或entities)
如果您只想要ID,您不需要实现Equals/GetHashCode;您可以直接调用。
people.SelectMany(p => p.States).Select(s => s.StateId).Distinct();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接