Reputation: 97
I am trying to calculate value through LINQ with two conditions, one of which happens to contain a foreach loop.
I've a list of integers statusList (stores StatCatId)
And based on the values in this list I want to add a where condition in my LINQ statement.
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();
Upvotes: 0
Views: 146
Reputation: 13381
Yet another way with 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();
Upvotes: 2
Reputation: 4797
Depending on the complexity of your calculation, you might use Contains, SelectMany, Sum, etc. , or plug in your own Func into your LINQ call.
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; }
}
or with an Func<>
Func<DataPoint, int> func = point => point.Condition ? point.Values.Sum() : point.Value;
var sum = data.Sum(s => func(s));
or if Func needs multiple steps:
Func<DataPoint, int> func = point =>
{
var retValue = point.Condition ? point.Values.Sum() : point.Value;
return retValue;
};
var sum = data.Sum(s => func(s));
Upvotes: 0
Reputation: 54887
You might be looking for the Contains
method:
var sListings =
(
from l in _colMgr.Listings.Values.AsEnumerable()
where (l.SystemPrice ?? 0) > 0
&& statusList.Contains(l.StatCatId)
select l
).ToList();
Upvotes: 4