如何使用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。
答案 0 :(得分:0)
您可以尝试将Qty
的最小值设为0
,并按升序模式排序Num
,然后取第一项。样本:
var item = LineItems.Where(x => x.Qty == 0).OrderBy(x => x.Num).First();
答案 1 :(得分:0)
尝试按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);
答案 2 :(得分:0)
如果您有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();