I am trying to count the VALUE
s corresponding to a List<int[]>
using Linq to Entity Framework.
- I have a
List<int[]>
where eachint[]
in theList
is of length 2. - I have a DB table
VALUES
which contains 3 columns, calledID
,PARENT
andVALUE
, where eachint[]
in theList
(see 1) may correspond to a record in the table, the 0 index beingID
and the 1 index beingPARENT
. *But some arrays likely do not correspond to any existing records in the table.
Each combination of ID
and PARENT
correspond to multiple DB records, with different VALUE
s.
Several points that are important to note:
- One of the problems is that I can't rely on
ID
alone - each value is defined/located according to both theID
andPARENT
. None of the int arrays repeat, though the value in each index may appear in several arrays, e.g.
List<int[]> myList = new List<int[]>(); myList.add(new int[]{2, 1}); myList.add(new int[]{3, 1}); //Notice - same "PARENT" myList.add(new int[]{4, 1}); //Notice - same "PARENT" myList.add(new int[]{3, 1}); //!!!! Cannot exist - already in the List
I can't seem to figure out how to request all of the VALUE
s from the VALUES
table that correspond to the ID
, PARENT
pairs in the List<int[]>
.
I've tried several variations but keep arriving at the pitfall of attempting to compare an array in a linq statement... I can't seem to crack it without loading substantially more information that I actually need.
Probably the closest I've gotten is with the following line:
var myList = new List<int[]>();
// ... fill the list ...
var res = myContext.VALUES.Where(v => myList.Any(listItem => listItem[0] == v.ID && listItem[1] == v.PARENT));
Of course, this can't work because The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities.
@chris huber
I tried it out but it was unsuccessful.
2 things:
- Where you created "myValues" I have a DB table entity, not a List.
- Due to point number 1, I am using LINQ to Entities, as opposed to LINQ to Object
My code then comes to something like this:
var q2 = from value in myContext.VALUES where myList.Select(x => new { ID = x.ElementAt(0), Parent = x.ElementAt(1) }).Contains(new { ID = value.ID, Parent = value.PARENT }) select value;
This returns the following error message when run:
LINQ to Entities does not recognize the method 'Int32 ElementAt[Int32](System.Collections.Generic.IEnumerable` 1[System.Int32],Int32)' method, and this method cannot be translated into a store expression.
@Ovidiu
I attempted your solution as well but the same problem as above:
As I am using LINQ to Entities, there are simply certain things that cannot be performed, in this case - the ToString() method is "not recognized". Removing the ToString() method and attempting to simply have a Int32 + "|" + In32
gives me a whole other error about LINQ to Entities not being able to cast an Int32 to Object.