【问题标题】:LINQ - .Any for class type list<string> and class type stringLINQ - .Any 用于类类型 list<string> 和类类型字符串
【发布时间】:2021-12-18 05:07:13
【问题描述】:

我有两节课

public class Cars
{
    public string Car{ get; set; }
    public List<string> CarEquipment{ get; set; }
}

public class Customers
{
    public string Customer { get; set; }
    public string OwnedEquipment{ get; set; }
}

我想检查是否有任何来自公共字符串列表(汽车类)的“CarEquipment”等于来自客户类的字符串公共字符串“OwnedEquipment”(布尔真或假)

下面的查询

(Cars.Select(x=>x.CarEquipment).Any(Customers.Select(x=>x.OwnedEquipment).Contains)

不幸的是,由于其中一个道具是字符串列表

【问题讨论】:

  • 你如何在 class Cars 而不是任何类型的枚举上调用 .Select()?您尝试使用哪个版本的 .Any() 需要一个集合而不是 lambda 函数?在这行代码中您要尝试做什么并不是很清楚。
  • 我在 list 上调用 .Select(),其中 list 中的道具是使用其他 LINQ 查询实现的。
  • 请出示minimal reproducible example 来证明问题并指出您遇到的确切错误,并描述您要达到的结果。

标签: linq


【解决方案1】:

快速检查:

var cars = new List<Cars>()
{ 
    new Cars { Car = "c1", CarEquipment = new List<string> { "a" } }, 
    new Cars { Car = "c2", CarEquipment = new List<string> { "a" } }
};

var customers = new List<Customers>() { new Customers { OwnedEquipment = "a" } };

var matchingCars = cars.Where(car => customers.Any(customer => car.CarEquipment.Contains(customer.OwnedEquipment)));
  • 第一个带有条件的过滤器(Where)
  • 客户自己的设备匹配汽车的汽车设备列表的条件(car => customers.Any(customer => car.CarEquipment.Contains(customer.OwnedEquipment)))

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2021-02-17
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多