Reputation: 4445
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.
Upvotes: 7
Views: 40033
Reputation: 125630
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));
Upvotes: 11
Reputation: 1362
It should be simply:
List<String[]> newListOfStrings = listOfStrings.where(x => x[0].Contains(identifer)).ToList()
The final ToList
is needed in this case because I have not used var
.
Upvotes: 1
Reputation: 754725
Try the following
var query = someCollection.Where(s => listOfStringArrays.Any(a => a[0] == s));
Upvotes: 3
Reputation: 12670
var firsts = listOfString.Select(x => x[0]);
var query = someCollection.Where(x => firsts.Contains(x));
This will project each array to it's first element, and then match from there
As a one liner:
var query = someCollection.Where(x => listOfString.Select(y => y[0]).Contains(x));
Upvotes: 1