简体   繁体   English

使用Linq查询List <List <string >>

[英]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. 我有一个字符串列表列表(例如List<List<string>> ) - 将其视为电子表格中的行和列。

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. 我想查询列(列表中的列表)(例如List<List<string>> )以查看字符串是否匹配,当它确实时,我想返回一个包含所有匹配的行和列的新列表行。 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). 基本上我让一个用户在列表上输入一个过滤器,然后它会显示匹配的所有行和列(它最好需要与任何列匹配,但我会很满意一个匹配的示例,说明此时的第一个col) 。
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). 我希望能够创建一个新的List<List<string>> ,其中包含正在应用的过滤器的结果(最好搜索所有列和行,但是对于刚检查第一列的示例感到满意)。 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. 所以,如果我的过滤器是"Ma"那么我应该得到一个包含2行的List<List<string>> (在这种情况下因为它匹配Mark和Marion)...我不希望列表返回只有Mark和Marion,我需要2行和2行的所有列。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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