Reputation: 31
I have the following scenario:
I get a collection of records from a data source and add them to a List
List<Entity> e = new List<Entity>();
foreach (var elm in datasource)
{
e.Add(new Entity { First = elm.First, Second = elm.Second, Third = elm.Third });
}
This gives me something like:
// -> First = John, Second = Sally, Third = Ingrid
// -> First = Sally, Second = Ingrid, Third = James
// -> First = Ingrid, Second = Sally, Third = James
I have an array of possible values that can be true and possible values that can be negative, in a List
List<string> positives = { "John", "Sally" }
List<string> negatives = { "Ingrid", "James" }
I am looking for an elegant why of matching the amount of positives and the amount of negatives I have in the generic list e, as per the above? Would something like this be possible with LINQ?
As I am not familiar with LINQ have no idea where to start. I tried something like:
var pos = e.SelectMany(s => s in positives).Count()
But this throws an exception.
Any help would be greatly appreciated
Upvotes: 3
Views: 1031
Reputation: 24832
or you can use an any
var pos = e.SelectMany(i =>
positives.Any(p=> p==i.First || p==i.Second || p==i.Third))
.Count();
Upvotes: 0
Reputation: 35822
SQL's in
clause in LINQ is Contains
method.
Test:
var pos = e.SelectMany(s => positives.Contains(s)).Count();
Seems that I haven't understood your question. Reading again.
To be honest, your question in not well-phrased.
But based on what I understood, I think the correct response is:
var pos = e.SelectMany(i => positives.Contains(i.First)
|| positives.Contains(i.Second)
|| positives.Contains(i.Third)).Count();
Upvotes: 3
Reputation: 13620
You are using in
incorrectly
e.SelectMany(s => positives.Contains(s)).Count();
but what I assue you are wanting is this
var pos = e.Count(s => positives.Contains(s.First) || positives.Contains(s.Second) ||positives.Contains(s.Third));
var neg= e.Count(s => negatives.Contains(s.First) || negatives.Contains(s.Second) ||negatives.Contains(s.Third));
Upvotes: 1