Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ search though a list of string arrays for a particular string

Tags:

arrays

c#

linq

I have a list of string arrays:

List<String[]> listOfStringArrays = something;

I need to select all objects from a collection that have a value which is equal to the string at the 0th index of any string array in the list.

For example, if I just had a simple list of strings, declared as:

List<String> listOfStrings = something;

I would just do:

var query = someCollection.Where(x => listOfStrings.Contains(x.id_num))

But obviously it's not as simple with a list of string arrays.

I know that I can easily just iterate through the list of string arrays and create a simple list of strings with the 0th value, like this:

List<String[]> listOfStringArrays = something;
List<String> listOfValues = new List<String>();

foreach (string[] s in listOfStringArrays)
    listOfValues.Add(s[0]);

var query = someCollection.Where(x => listOfValues.Contains(x => x.id_num);

But would really like to avoid this and am trying to write it as a one liner without introducing extra lists and loops.

like image 469
dursk Avatar asked Jan 10 '14 22:01

dursk


1 Answers

You can put it all into one query:

someCollection.Where(x => listOfValues.Select(y => y[0]).Contains(x => x.id_num);

But it will iterate over listOfValues over and over again.

I would rather go with HashSet<string> to make it faster:

var set = new HashSet<string>(listOfValues.Select(y => y[0]));
someCollection.Where(x => set.Contains(x));
like image 199
MarcinJuraszek Avatar answered Sep 29 '22 03:09

MarcinJuraszek