gpt4 book ai didi

c# - 为什么我在执行交集时得不到结果?

转载 作者:行者123 更新时间:2023-11-30 17:43:00 25 4
gpt4 key购买 nike

用户类:

public class User  
{
public int ID { get; set; }
public string Email { get; set; }
}

代码:

        var usersL = new List<User>()
{
new User{ID = 1,Email = "abc@foo.com"},
new User{ID = 2,Email = "def@foo.com"}
};

var usersR = new List<User>()
{
new User{ID = 1,Email = "abc@foo.com"},
new User{ID = 2,Email = "def@foo.com"}
};

var both = (from l in usersL select l)
.Intersect(from users in usersR select users);

foreach (var r in both)
Console.WriteLine(r.Email);

返回 0 个结果。

我知道我可以通过使用 join 来完成类似的事情,但我想使用 Intersect 因为 A) 这最终会在一些数据库代码上起作用,我们想使用这个函数(太长了进入原因)和 B)我只是很好奇为什么 Intersect 在这里不起作用。

        var both = from l in usersL
join r in usersR on l.ID equals r.ID
select l;

最佳答案

.Net 为预定义类型提供了比较逻辑。在您的连接查询的情况下,您正在连接(比较)两个 Int 类型(预定义类型)的 ID

var both = from l in usersL
join r in usersR on l.ID equals r.ID
select l;

在交叉查询的情况下,您正在尝试比较两个用户定义的用户类型的自定义对象。因此,您需要提供自己的自定义比较实现逻辑。

2种方法来解决这个问题......

选项 1:实现 IEqualityComparer

public class User
{
public int ID { get; set; }
public string Email { get; set; }
}

public class MyEqualityComparer : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
if (object.ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
return x.ID.Equals(y.ID) &&
x.Email.Equals(y.Email);
}

public int GetHashCode(User u)
{
return new { u.ID, u.Email }.GetHashCode();
}
}

class Program
{
static void Main(string[] args)
{

var usersL = new List<User>()
{
new User{ID = 1,Email = "abc@foo.com"},
new User{ID = 2,Email = "def@foo.com"}
};

var usersR = new List<User>()
{
new User{ID = 1,Email = "abc@foo.com"},
new User{ID = 2,Email = "def@foo.com"}
};

var both = (from l in usersL select l)
.Intersect(from users in usersR select users, new MyEqualityComparer());

foreach (var r in both)
Console.WriteLine(r.Email);
}
}

选项 2:覆盖自定义对象本身的 Equals 和 GetHashcode 方法

public class User 
{
public int ID { get; set; }
public string Email { get; set; }

public override bool Equals(Object obj)
{
// Check for null values and compare run-time types.
if (obj == null || GetType() != obj.GetType())
return false;

User x = (User)obj;
return (ID == x.ID) && (Email == x.Email);
}

public override int GetHashCode()
{
return new { ID, Email }.GetHashCode();
}
}

class Program
{
static void Main(string[] args)
{

var usersL = new List<User>()
{
new User{ID = 1,Email = "abc@foo.com"},
new User{ID = 2,Email = "def@foo.com"}
};

var usersR = new List<User>()
{
new User{ID = 1,Email = "abc@foo.com"},
new User{ID = 2,Email = "def@foo.com"}
};

var both = (from l in usersL select l)
.Intersect(from users in usersR select users);

foreach (var r in both)
Console.WriteLine(r.Email);
}
}

希望这对您有所帮助。

关于c# - 为什么我在执行交集时得不到结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com