gpt4 book ai didi

c# - LINQ 项目属性转换为包含的新匿名类型

转载 作者:行者123 更新时间:2023-11-30 14:53:35 25 4
gpt4 key购买 nike

我有以下代码,我正在尝试使其工作,但它仍然无法编译。谢谢。

List<Employee> emploees = new List<Employee>() 
{
new Employee { ID = 101, Name = "Rosy" },
new Employee { ID = 102, Name = "Sury" }
};

var result = emploees.Select(x=> new {x.ID, x.Name}).Contains(new Employee { ID = 101, Name = "Rosy" });
Console.WriteLine(result);

最佳答案

首先,您不需要将列表项投影到匿名对象。此外,IMO Any()Contains() 更适合这种情况:

var result = emploees.Any(x => x.ID == 101 && x.Name == "Rosy");

如果您仍想使用 Contains,则需要为 Employee 类创建comparer

sealed class MyComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (x == null)
return y == null;
else if (y == null)
return false;
else
return x.ID == y.ID && x.Name == y.Name;
}

public int GetHashCode(Employee obj)
{
unchecked
{
int hash = 17;
hash = hash * 23 + obj.ID.GetHashCode();
hash = hash * 23 + obj.Name.GetHashCode();
return hash;
}
}
}

并将您的代码更改为:

  var result = emploees.Contains(new Employee { ID = 101, Name = "Rosy" }, new MyComparer());

关于c# - LINQ 项目属性转换为包含的新匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28918572/

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