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

LINQ Project properties into a new anonymous type with Contains

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

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创建comparerclass.

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());

为什么要投影到匿名类型然后进行类型比较检查?

您可以简单地使用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,请为您的Employee覆盖IEquatable class:

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);