[英]filtering list based on two different data columns linq C#
How do I filter an item from a list based on two different columns one being a number(smallest number) using 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; }
}
I want to filter this list and get a LineItem based on Qty = 0 and smallest num value. 我想过滤此列表并获取基于Qty = 0和最小num值的LineItem。
You could try to get the min value for Qty
is 0
and order by Num
in ascending mode, then taking the first item. 您可以尝试获取
Qty
的最小值为0
,并按Num
升序排列,然后取第一项。 For sample: 样品:
var item = LineItems.Where(x => x.Qty == 0).OrderBy(x => x.Num).First();
Try filtering by Qty == 0
, sorting according to Num
and keep the first one: 尝试按
Qty == 0
过滤,并根据Num
排序,并保留第一个:
var lineItem = LineItems.Where(l => l.Qty == 0).OrderBy(l => l.Num).FirstOrDefault();
or just keep the first that Qty
equals to 0
and Num
equals to minimum possible: 或只保留第一个,即
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);
If you have your LineItem class implement IComparable<T>
, then you can do something like this: 如果您有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;
}
}
then 然后
var item = l.LineItems.Where(p => p.Qty == 0).Min();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.