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?
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
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.
var resultList = fullNameList.Where(r => searchList.Any(f=>r.StartsWith(f)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With