我有以下代码,我正在努力工作,但它仍然无法编译。谢谢。
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);
答案 0 :(得分:3)
首先,您不需要将列表项目投影到匿名对象。
此外,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());
答案 1 :(得分:2)
为什么要投射到匿名类型然后进行类型比较检查?
您只需使用Any
即可获得所需内容:
var result = emploees
.Select(x=> new {x.ID, x.Name})
.Any(x => x.ID == 101 && x.Name == "Rosy");
Console.WriteLine(result);
或者简单地说,没有Select
,因为您只使用bool
:
bool result = emploees
.Any(x => x.ID == 101 && x.Name == "Rosy");
Console.WriteLine(result);
为了完整起见,如果您真的想要使用Contains
,请覆盖IEquatable
类的Employee
:
public class Employee : IEquatable<Employee>
{
public bool Equals( Employee other)
{
return this.ID == other.ID &&
this.Name == other.Name;
}
}
然后做:
var result = emploees
.Select(x => new Employee {x.ID, x.Name})
.Contains(new Employee { ID = 101, Name = "Rosy" });
Console.WriteLine(result);