-1

I have a local list of Ids and I need to check existence of this Ids in DB.Table.

I wrote following code:

List<int> localIdList;
//filling localIdList
var idArrayFromDb = DB.Table
                     .Select(s => s.ID)
                     .ToArray();
bool isSubset = !localIdList
                .Except(idListFromDb)
                .Any();

For now it works well, but I believe it's not the best way to solve this problem.

So I'm wondering, can I do the same without gathering a collection of Ids from DB or some any better way?

LANimal
  • 71
  • 6

2 Answers2

0

One way to do this will be by using Contain() method of List<>.

bool isSubset = DB.Table.Where(s => localIdList.Contains(s)).Any();

One drawback as mentioned by @CodeCaster 1 is that it will be limited by the length of the localIdList.

cpr43
  • 2,942
  • 1
  • 18
  • 18
  • Whether this works depends on the size of the ID list. SQL Server has limitations on how many values you can use in an IN() clause. Also, "Try" is not an answer, explain what your code is doing. – CodeCaster Oct 31 '17 at 07:48
-1

Try this

//sample
        List<int> t1 = new List<int>();
        t1.Add(1);
        t1.Add(2);
        t1.Add(3);

        List<int> t2 = new List<int>();
        t2.Add(2);

        bool res = t2.Any(a => t1.Any(b => b == a));
        Console.WriteLine("res :" + res);

    // your solution here
    bool isSubset  = DB.Table.Any(s => localIdList.any(l=> l == s.ID));
i3lai3la
  • 980
  • 6
  • 10