Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 680
leora Avatar asked Apr 11 '15 12:04

leora


People also ask

What does != Mean in C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is ?: operator in C?

In other words, we can also say that an operator is a symbol that tells the compiler to perform specific mathematical, conditional, or logical functions. It is a symbol that operates on a value or a variable. For example, + and - are the operators to perform addition and subtraction in any C program.


Video Answer


1 Answers

var resultList = fullNameList.Where(r => searchList.Any(f=>r.StartsWith(f)));
like image 75
ASh Avatar answered Oct 18 '22 18:10

ASh