[英]filtering list based on two different data columns linq C#
如何使用LINQ C#基于两个不同的列(其中一个是数字(最小数字))从列表中过滤项目?
public class Line
{
public int Id { get; set; }
public List<LineItem> LineItems { get; set; }
public Line()
{
LineItems = new List<LineItem> {
new LineItem{Num = 1, Name="i", Qty = 0, Active = false},
new LineItem{Num = 2, Name="j", Qty = 2,Active = false},
new LineItem{Num = 3, Name="k", Qty = 3,Active = false},
};
}
}
public class LineItem
{
public int Num { get; set; }
public string Name { get; set; }
public int Qty { get; set; }
public bool Active { get; set; }
}
我想过滤此列表并获取基于Qty = 0和最小num值的LineItem。
您可以尝试获取Qty
的最小值为0
,并按Num
升序排列,然后取第一项。 样品:
var item = LineItems.Where(x => x.Qty == 0).OrderBy(x => x.Num).First();
尝试按Qty == 0
过滤,并根据Num
排序,并保留第一个:
var lineItem = LineItems.Where(l => l.Qty == 0).OrderBy(l => l.Num).FirstOrDefault();
或只保留第一个,即Qty
等于0
且Num
等于最小可能值:
var minNum = LineItems.Where(l => l.Qty == 0).Min(l => l.Num);
var lineItem = LineItems.FirstOrDefault(l => l.Qty == 0 && l.Num == minNum);
如果您有LineItem类实现IComparable<T>
,则可以执行以下操作:
public class LineItem : IComparable<LineItem>
{
public int Num { get; set; }
public string Name { get; set; }
public int Qty { get; set; }
public bool Active { get; set; }
public int CompareTo(LineItem other)
{
if (other.Num > this.Num)
return -1;
else if (other.Num == this.Num)
return 0;
else
return 1;
}
}
然后
var item = l.LineItems.Where(p => p.Qty == 0).Min();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.