简体   繁体   中英

Using Linq to query a List<List<string>>

I have a list of list of strings (eg List<List<string>> ) - think of it as rows and columns in a spreadsheet.

The lists are dynamically created so the number of rows and columns can change.

I want to query the columns (the list within the list) (eg List<List<string>> ) to see if a string matches, when it does then I want to return a new list that contains all the matching rows and columns within the rows. Basically I am letting a user enter a filter on a list and it will then display all the rows and columns that match (it needs match against any column preferably but I will be happy with an example that matches say the first col at this point).
I have tried several examples but they all just seem to return the columns as a list but no outer list above that (the rows).

Any help would be appreciated :)

Here is an example of the scenario using data

ColumnA   ColumnB     ColumnC
Mark       Australia   25
Marion     America     30
Fred       Dave        35

I want to be able to create a new List<List<string>> that contains the results of a filter being applied (preferably searching across all columns and rows but would be happy with an example that just checked the first column). So if my filter was "Ma" then I should get a List<List<string>> back that contains 2 rows (in this case because it matches Mark and Marion) ... I don't want a list back that only has Mark and Marion, I need the 2 rows and all the columns for the 2 rows.

If all you need is to find a value in all lists and return the whole list if it was found:

string search = txtUserSearch.Text.Trim();
List<List<string>> searchResult = allLists
    .Where(list => list.Any(s => search.Equals(s, StringComparison.CurrentCultureIgnoreCase)))
    .ToList();

If you don't need the case-insensitive search you can use:

.Where(list => list.Contains(search))

If you even want to find partial matches (substrings), you can use this:

.Where(list => list.Any(s => s != null && s.Contains(search)))

or case-insensitive:

.Where(list => list.Any(s => s != null && s.IndexOf(search, StringComparison.CurrentCultureIgnoreCase) >= 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM