3

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

0

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

0

or you can use an any

var pos = e.SelectMany(i => 
    positives.Any(p=> p==i.First || p==i.Second || p==i.Third))
    .Count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.