Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Where condition to match array

I have a linq list obtained from database in my Model. Now I have a string array obtained from my controller. I want to construct a statement

pseudo-code

List<object> objlist = db.objects.tolist();
string[] strarray; // obtained from a long code.
var k = objlist.Where(u => u.somecol == strarray[0] || u.somecol == strarray[1]........strarray[n]).toList();

I am little bit confused how to accomplish this since my strarray[] is variable length and can contain upto 1000 words.

like image 327
Flood Gravemind Avatar asked Aug 17 '13 11:08

Flood Gravemind


2 Answers

You can check if an array contains some item using the Array.IndexOf<T> Method:

bool strarrayContainsX = Array.IndexOf<string>(strarray, "X") >= 0;

However, I'd recommend you use a HashSet<string> instead of a string array for anything more than a few items. The HashSet<T> Class provides a Contains Method to check if a set contains some item:

HashSet<string> strset = new HashSet<string>(strarray);
bool strsetContainsX = strset.Contains("X");

The resulting query then looks like this:

var k = objlist.Where(u => strset.Contains(u.somecol)).ToList();
like image 171
dtb Avatar answered Sep 22 '22 00:09

dtb


Use Contains:

var k = objlist.Where(u => strarray.Contains(u.somecol)).toList();
like image 31
Zbigniew Avatar answered Sep 22 '22 00:09

Zbigniew