简体   繁体   English

在C#中,如何使用另一个列表的StartsWith()条件过滤列表?

[英]In C#, how can I filter a list using a StartsWith() condition of another list?

Lets say I have a list of strings: 假设我有一个字符串列表:

var searchList = new List<string>();
searchList.Add("Joe"):
searchList.Add("Bob");

and I have another list 我有另一个清单

var fullNameList = new List<string>();
fullNameList.Add("Joe Thompson"):
fullNameList.Add("Bob Jones");
fullNameList.Add("Bob Smith");
fullNameList.Add("Billy Smith");
fullNameList.Add("Joe Williams");

I now want to filter the fullNameList based on if it exists in the search list but I am not doing a direct match but rather a "starts with" match. 我现在想根据它是否存在于搜索列表中来过滤fullNameList,但我没有进行直接匹配,而是“匹配”。 So in my example, after filtering I would want this to be the results 所以在我的例子中,过滤后我希望这是结果

"Joe Thompson"
"Bob Jones"
"Bob Smith"
"Joe Williams"

(as you can see the record starting with Billy was not included as it didn't start with any items in the search list) (你可以看到从比利开始的记录没有包括在内,因为它没有从搜索列表中的任何项目开始)

I could do this "manually" like this: 我可以像这样“手动”执行此操作:

 var resultList = fullNameList.Where(r=> r.StartsWith("Joe") || r.StartsWith("Bob"));

but I want it to be dynamic (as there might be more items in the search list added in the future). 但我希望它是动态的(因为将来可能会在搜索列表中添加更多项目)。

I could do this in a loop like this: 我可以在这样的循环中执行此操作:

 var resultsList = new List<string>();

 foreach (var item in searchList)
 { 
      resultsList.AddRange(fullNameList.Where(r=>r.StartsWith(item));
 } 

but wanted to see if there anyway to do a Startswith on a list as opposed to a single string in a single line of linq code? 但是想看看是否还有一个列表上的Startswith而不是单行linq代码中的单个字符串?

var resultList = fullNameList.Where(r => searchList.Any(f=>r.StartsWith(f)));

就像是:

fullNameList.Where(c=>searchList.Any(f=>c.StartsWith(f))) 

The following LINQ query seems literate-programming-like to me and pretty straightforward to read & maintain later,: 以下LINQ查询对我来说似乎是文字编程 - 并且以后非常简单易读:

var searchList = new List<string> { "Joe", "Bob" };

var fullNameList = new List<string>
    {
        "Joe Thompson",
        "Bob Jones",
        "Bob Smith",
        "Billy Smith",
        "Joe Williams"
    };

var joesAndBobs = from name in fullNameList
                  from firstName in searchList
                  where name.StartsWith(firstName)
                  select name;

foreach (string str in joesAndBobs)
    Console.WriteLine(str);

However, it may perform worse than solutions previously posted. 但是,它可能比以前发布的解决方案更糟糕。 They use .Any() method of IEnumerable<T> , it stops after finding the first matching first name for any dude, while mine continues through all the Joes, Bobs and Mikes anyway. 他们使用IEnumerable<T> .Any()方法,它在为任何一个家伙找到第一个匹配的名字后停止,而我仍然继续通过所有Joes,Bobs和Mikes。

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

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