Reputation: 368
I have a List<string[]> called myList:
[0] "ABC" "Item Description Here" "Item Code Here"
[1] "DEF" "Item Description Here" "Item Code Here"
[3] etc, etc...
This is how I populated myList:
...
while (myReader.Read())
{
string[] row = new string[myInt];
for (int i = 0; i < myInt; i++)
{
row[i] = myReader[i].ToString();
}
myList.Add(row);
}
...
Now I need to search through myList and return a new List<string[]> called newList[] that contains 1 or more string[] where the first string matches a keyword ("ABC", "DEF", etc). How do I do that?
Upvotes: 1
Views: 236
Reputation: 18563
1) If you are searching only for one keyword:
var result = myList.Where(s=>s[0].Equals("\"ABC\"")).ToList();
2) If checklist
contains same number of elements as myList
:
List<string> checklist = new List<string>() {"ABC","DEF"};
var result = myList.Where((s,i)=>s[0].Equals(checklist[i])).ToList();
3) If it can match any keyword from a checklist than:
var result = myList.Where(s=>checklist.Contains(s[0])).ToList();
Upvotes: 3
Reputation: 58645
var result = myList.Where(s=> s.Length >= 1 && s[0].Equals("ABC")).ToList();
Upvotes: 2
Reputation: 75326
Define list of keywords:
var keywords = List<string>() {"ABC", "DEF", ...};
Then you can use LINQ to filter:
var newList = list.Where(ar => keywords.Contains(ar.First());
Or:
var newList = list.Where(ar => keywords.Any(k => k.Equals(ar.First()));
Upvotes: 3