Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use List<Tuple<int, int>> to return data in Linq

Tags:

c#

linq

Given:

List<int> myList;

If I wanted to return data where the record ID was contained in this list I would simply do:

var q = db.Table.Where(c=> myList.Contains(c.ID));

However, given:

List<Tuple<int, int>> myList;

How would I write a Linq query to return records where both conditions are met? With one data point I would write:

var q = db.Table.Where(c=>
            c.ID == myList.Item1
            && c.AnotherValue == myList.Item2);

How would I convert the above statement to work on a List<Tuple<int, int>>?

like image 483
Tom Gullen Avatar asked May 25 '16 14:05

Tom Gullen


2 Answers

A Tuple is a structure that can't not be translated to sql by your Linq Provider. A solution could be making a switch to Linq to Objects

var q = db.Table.AsEnumerable()
                .Where(c=> myList.Any(tuple => c.ID == tuple.Item1 &&
                                           c.AnotherValue == tuple.Item2));

But the bad thing about this solution is that you're going to load all the rows from that table to filter in memory.

Another solution could be using Linqkit:

var predicate = PredicateBuilder.False<Table>();

foreach (string t in myList)
{
    predicate = predicate.Or(c =>c.ID == t.Item1 && c.AnotherValue == t.Item2));
}

db.Table.AsExpandable().Where(predicate);

You will find more info about this last solution in this link

like image 105
octavioccl Avatar answered Nov 18 '22 09:11

octavioccl


var q = db.Table.AsEnumerable().Where(c => myList.Any(tuple => c.ID == tuple.Item1 &&
                                               c.AnotherValue == tuple.Item2));

With Any you can check if there is at least one element in myList the matches your condition.

But as @octaviocci pointed out, this is not translatable to SQL, so you would need to call AsEnumerable() before and do the filtering locally, which may not be what you want if there are a lot of irrelevant records.

like image 1
René Vogt Avatar answered Nov 18 '22 10:11

René Vogt