我试图通过LINQ计算两个条件的值,其中一个恰好包含一个foreach循环。
我有一个整数列表statusList(存储StatCatId)
根据此列表中的值,我想在LINQ语句中添加where条件。
var sListings = (from l in _colMgr.Listings.Values.AsEnumerable()
where (l.SystemPrice ?? 0) > 0 &&
// Need to add condition like foreach(s in statusList) if l.StatCatId == s
select l).ToList();
答案 0 :(得分:4)
您可能正在寻找Contains
方法:
var sListings =
(
from l in _colMgr.Listings.Values.AsEnumerable()
where (l.SystemPrice ?? 0) > 0
&& statusList.Contains(l.StatCatId)
select l
).ToList();
答案 1 :(得分:2)
使用join clause
var sListings =
(
from l in _colMgr.Listings.Values.AsEnumerable()
join s in statusList on l.StatCatId equals s
where (l.SystemPrice ?? 0) > 0
select l
).ToList();
答案 2 :(得分:0)
根据计算的复杂程度,您可以使用Contains,SelectMany,Sum等,或者将您自己的Func插入LINQ调用。
class Program
{
static void Main(string[] args)
{
var data = new List<DataPoint>
{
new DataPoint(){Condition = true, Value = 0, Values = new List<int>{1,2,3}},
new DataPoint(){Condition = false, Value = 10, Values = new List<int>{}},
new DataPoint(){Condition = true, Value = 0, Values = new List<int>{4,5}},
new DataPoint(){Condition = false, Value = 20, Values = new List<int>{}}
};
var sum = data.Sum(s=>s.Condition?s.Values.Sum():s.Value);
}
}
internal class DataPoint
{
public bool Condition { get; set; }
public int Value { get; set; }
public List<int> Values { get; set; }
}
或使用Func&lt;&gt;
Func<DataPoint, int> func = point => point.Condition ? point.Values.Sum() : point.Value;
var sum = data.Sum(s => func(s));
或者如果Func需要多个步骤:
Func<DataPoint, int> func = point =>
{
var retValue = point.Condition ? point.Values.Sum() : point.Value;
return retValue;
};
var sum = data.Sum(s => func(s));