Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有不同结果集的LINQ连接_C#_Linq - Fatal编程技术网

C# 具有不同结果集的LINQ连接

C# 具有不同结果集的LINQ连接,c#,linq,C#,Linq,我有个问题。我和林克相处得不好。我有两门课: [Person] string FirstName {get;set;} string LastName {get;set;} IEnumerable<State> LastName {get;set;} [State] int StateID {get;set;} string StateName {get;set;} 在此方面的任何帮助都将不胜感激。如下: people.SelectMany(p => p.States).D

我有个问题。我和林克相处得不好。我有两门课:

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

[State]
int StateID {get;set;}
string StateName {get;set;}
在此方面的任何帮助都将不胜感激。

如下:

people.SelectMany(p => p.States).Distinct();
请注意,您需要在
State
类中正确实现
Equals
GetHashCode
。(除非您使用LINQ to SQL或实体)

如果只需要ID,则不需要实现
Equals
/
GetHashCode
;你只要打个电话就可以了

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

Linq distinct很烦人,您必须在要distinct()的类上实现IEqualityComparer接口,然后获得所指的distinct选择的方式是:

IEnumerable<Person> people = GetPeople();
people.SelectMany((person) => person.LastName).Distinct();
IEnumerable people=GetPeople();
people.SelectMany((person)=>person.LastName.Distinct();
SelectMany()将合并枚举的结果展平,这样您就不会得到IEnumerable,而是得到IEnumerable

在实现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
{
int StateID{get;set;}
字符串StateName{get;set;}
public bool Equals(State x,State y){返回x.StateID==y.StateID&&x.StateName==y.StateName;}
public int GetHashCode(State obj){return obj.StateId;}
}
请记住,如果不实现IEqualityComparer,distinct()将对您毫无帮助。

尝试以下方法:

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

感谢您的回复,正如您所说的,关键是创建您自己的实现。