【问题标题】:Filter list with Linq使用 Linq 过滤列表
【发布时间】:2016-12-09 02:17:58
【问题描述】:

我有课:

public class Car
{
    public string Color { get; set; }

        public string Speed { get; set; }
}

还有一个例子:

List<Car> Cars = new List<Car>()
{
     new Car()
     {
           Color = "Green".
           Speed = "100"
      }, 
      new Car()
     {
           Color = "Yellow".
           Speed = "150"
      }
}

我要过滤这个列表

我愿意:

List<Car> Conditions = new List<Car>()
{
     new Car()
     {
           Color = "Green".
           Speed = "100"
     }, 
     new Car()
     {
           Color = "Yellow".
           Speed = "100"
     }, 
     .......
}

如何浏览我的列表并只选择至少符合 Linq 条件的汽车?

这里只以我列表的第一个索引为例

我的预期输出:

  List<Car> Cars = new List<Car>()
    {
         new Car()
         {
               Color = "Green".
               Speed = "100"
          }
    }

因为颜色和速度与Conditions 的一个索引匹配

【问题讨论】:

标签: c# linq


【解决方案1】:

如果你需要一套车

var result = Cars
    .Where(car=>Conditions.Any(cond=>
        cond.Speed == car.Speed && cond.Color == car.Color)).ToArray();

如果你只需要从一组匹配你的条件的车

var result = Cars
    .FirstOrDefault(car=>Conditions.Any(cond=>
        cond.Speed == car.Speed && cond.Color == car.Color));

【讨论】:

  • "如何浏览我的列表,只选择至少符合 Linq 条件的汽车?"所以var result = Cars .FirstOrDefault(car=&gt;Conditions.Any(cond=&gt; cond.Speed == car.Speed &amp;&amp; cond.Color == car.Color))
【解决方案2】:
var FilteredCars = Cars
    .Where(car => Conditions.Any(c => car.Color == c.Color && car.Speed == c.Speed));

如果Car 会以这种方式覆盖Equals + GetHashCode,您也可以这样使用:

var FilteredCars = Cars.Where(Conditions.Contains);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多