C#使用字符串列表筛选字符串列表的列表 [英] C# filter list of string lists using a string list
本文介绍了C#使用字符串列表筛选字符串列表的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿那里,
我有一个数据视图,它由一个使用字符串列表的对象填充。我想通过在文本框中输入搜索词来选择合适的条目。
我的对象:
Hey there,
I have a dataview which is filled by an object using string lists. I want pick the suitable entries by typing search words in a textbox.
my object:
class my_object
{
List<string> column1 = new List<string>();
List<string> column2 = new List<string>();
List<string> column3 = new List<string>();
List<string> column4 = new List<string>();
}
我的数据视图条目:
my entries for the dataview:
List<my_object> entries = new List<my_object>();
我的目的是过滤像Windows资源管理器中的搜索功能这样的条目,但区别在于我想要包含四列,而不仅仅是带有文件名的列。
是否有有没有可能做到这一点?
希望你能帮帮我。
我有什么尝试过:
My aim is to filter the entries like the search function in the windows explorer but with the difference that i want to include four columns an not just the column with the filename.
Is there any possibility to do this?
Hope you can help me.
What I have tried:
internal static List<my_object> SearchObject(this List<my_object> Source, List<string> SearchWords)
{
List<my_object> results = new List<my_object>();
foreach (my_object m in Source)
{
foreach(string s in SearchWords)
{
// Filter Column 1
foreach(string c1 in m.column1)
{
if(c1.IndexOf(s) != -1)
{
results.Add(m);
break;
}
}
}
}
return results;
// Problem:
// This function only filters the first column.
// If I want to filter the next column, I have to break all 'foreach' blocks
// except the '(my_object m in Source)' block...
// It the 'break' would work for more the one loop, this method would work...
}
推荐答案
您好,我认为结果列表应包含每列的匹配项?
如果您使用的是C#,可能应该有没有问题使用Linq
Hi, I think result List should contain matches from each column?
If you're using C#, probably should have no problems using Linq
//Source in this case refers to each column
//SearchWords list of strings to search
public List<string> SearchList(List<string> Source, List<string> SearchWords){
//your code can be shortened to Linq query similar to the following
List<string> results = Source.Where(x => SearchWords.Contains(x)).ToList();
//in sql this would translate similiar to:
//select Source.Value
//from Source
//where Source.Value in ('Value1', 'Value2') --SearchWords
return results;
}
Regarding SearchObject, what is the use of passing List<my_object> Source when it seems you need only 1 my_object?
You can use the Linq query for the 4 lists in my_object.
my_object data = new my_objec(); //lists containing all data
List<my_object> entries = new List<my_object>();
So then
entries.column1 = SearchList(data.column1, SearchWords); //similar for the rest
这篇关于C#使用字符串列表筛选字符串列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文