Reputation: 3384
I need help with a specific LINQ query (I still suck at em'!)
Background Info:
I've got a class DataEntry:
class DataEntry{
public Attribute Attribute{get; set;}
public List<object> Data{get; set;}
Attribute Class:
class Attribute{
public string FeatureName{get; set;}
public Types FeatureType{get; set;}
public List<object> PossibleValues{get; set;}
What i'll eventually have is about ~20 different data entries with about 1000 data objects per entry. What I'm trying to do is write a LINQ query to select a specific data entry based on the FeatureType and then give me a count of the total number of data items of that entry equal to a specific value.
What i'm trying to get is the count of the "high" and count of the "low" values from the data entry that has a featuretype equal to "foobar".
The closest I've gotten is:
int count = dataset.SelectMany(i => i.Data).Count(j => j.ToString() == "high");
Which gives me the count of "high", but doesn't filter by featuretype.
Is it possible? Is it possible to do in a single statement?
Upvotes: 1
Views: 1331
Reputation: 422222
You are on the right track. Just add a Where
method to filter out stuff before feeding them to SelectMany
.
dataset.Where(i => i.Attribute.FeatureType == Types.FooBar)
.SelectMany(i => i.Data)
.Count(j => j.ToString() == "high")
To calculate high and low in a single statement, you can try:
dataset.Where(i => i.Attribute.FeatureType == Types.FooBar)
.SelectMany(i => i.Data)
.Select(i => i.ToString())
.Aggregate(new { High = 0, Low = 0 },
(acc, i) => val == "high" ? new { High = i.High + 1, i.Low }
: val == "low" ? new { i.High, Low = i.Low + 1 } : acc);
Upvotes: 3
Reputation: 5374
Another way:
int count =
( from dataEntry in dataset
from data in dataEntry.Data
where dataEntry.Attribute.FeatureType == Types.Foo && data.ToString() == "high"
select data
).Count();
Upvotes: 2