compare list of strings with another string - c#

I have 1 long string which looks like :"item1, item7, item9" etc.
Then I have a list which looks like:
"item2",
"item3",
"item9"
I want to run a check to see if any of the list strings match anything within the long string. I could use a foreach loop, but I'm thinking there must be an easy LINQ expression which I can't seem to get right.

You could try something like this:
var isContained = list.Any(x=>stringValue.Contains(x));
where list is the list of strings, stringValue is the string you have.
In the above code, we use the Any method, which looks if there is any element in the list that makes the predicate we supply to be true. The predicate has as input a list item and check if this item is contained in the stringValue. If so that returns true. Otherwise false.

string longString = "item1,item7,item9";
List<string> myList=new List<string>(new string[]{"item2","item3","item9"});
if (myList.Any(str => longString.Contains(str)))
{
Console.WriteLine("success!");
}
else
{
Console.WriteLine("fail!");
}

How about:
// Set up the example data
String searchIn = "item1, item7, item9";
List<String> searchFor = new List<String>();
searchFor.Add("item2");
searchFor.Add("item3");
searchFor.Add("item9");
var firstMatch = searchFor.FirstOrDefault(p => { return -1 != searchIn.IndexOf(p); });
// firstMatch will contain null if no item from searchFor was found in searchIn,
// otherwise it will be a reference to the first item that was found.

Related

Unity Lists Finding 2 letters in a list containing 5 letter words [duplicate]

I have a list like so and I want to be able to search within this list for a substring coming from another string. Example:
List<string> list = new List<string>();
string srch = "There";
list.Add("1234 - Hello");
list.Add("4234 - There");
list.Add("2342 - World");
I want to search for "There" within my list and return "4234 - There". I've tried:
var mySearch = list.FindAll(S => s.substring(srch));
foreach(var temp in mySearch)
{
string result = temp;
}
With Linq, just retrieving the first result:
string result = list.FirstOrDefault(s => s.Contains(srch));
To do this w/o Linq (e.g. for earlier .NET version such as .NET 2.0) you can use List<T>'s FindAll method, which in this case would return all items in the list that contain the search term:
var resultList = list.FindAll(delegate(string s) { return s.Contains(srch); });
To return all th entries:
IEnumerable<string> result = list.Where(s => s.Contains(search));
Only the first one:
string result = list.FirstOrDefault(s => s.Contains(search));
What you've written causes the compile error
The best overloaded method match for 'string.Substring(int)' has some invalid arguments
Substring is used to get part of string using character position and/or length of the resultant string.
for example
srch.Substring(1, 3) returns the string "her"
As other have mentioned you should use Contains which tells you if one string occurs within another. If you wanted to know the actual position you'd use IndexOf
same problem i had to do.
You need this:
myList.Where(listStrinEntry => myString.IndexOf(listStringEntry) != -1)
Where:
myList is List<String> has the values
that myString has to contain at any position
So de facto you search if myString contains any of the entries from the list.
Hope this is what you wanted...
i like to use indexOf or contains
someString.IndexOf("this");
someString.Contains("this");
And for CaseSensitive use:
YourObj yourobj = list.FirstOrDefault(obj => obj.SomeString.ToLower().Contains("some substring"));
OR
YourObj yourobj = list.FirstOrDefault(obj => obj.SomeString.ToUpper().Contains("some substring"));

Check if a particular string is contained in a list of strings

I'm trying to search a string to see if it contains any strings from a list,
var s = driver.FindElement(By.Id("list"));
var innerHtml = s.GetAttribute("innerHTML");
innerHtml is the string I want to search for a list of strings provided by me, example
var list = new List<string> { "One", "Two", "Three" };
so if say innerHtml contains "One" output Match: One
You can do this in the following way:
int result = list.IndexOf(innerHTML);
It will return the index of the item with which there is a match, else if not found it would return -1.
If you want a string output, as mentioned in the question, you may do something like:
if (result != -1)
Console.WriteLine(list[result] + " matched.");
else
Console.WriteLine("No match found");
Another simple way to do this is:
string matchedElement = list.Find(x => x.Equals(innerHTML));
This would return the matched element if there is a match, otherwise it would return a null.
See docs for more details.
You can do it with LINQ by applying Contains to innerHtml for each of the items on the list:
var matches = list.Where(item => innerHtml.Contains(item)).ToList();
Variable matches would contain a subset of strings from the list which are matched inside innerHtml.
Note: This approach does not match at word boundaries, which means that you would find a match of "One" when innerHtml contains "Onerous".
foreach(var str in list)
{
if (innerHtml.Contains(str))
{
// match found, do your stuff.
}
}
String.Contains documentation
For those who want to serach Arrray of chars in another list of strings
List WildCard = new() { "", "%", "?" };
List PlateNo = new() { "13eer", "rt4444", "45566" };
if (WildCard.Any(x => PlateNo.Any(y => y.Contains(x))))
Console.WriteLine("Plate has wildchar}");

Using List<string>.Any() to find if a string contains an item as well as find the matching item?

I have a list of strings, which can be considered 'filters'.
For example:
List<string> filters = new List<string>();
filters.Add("Apple");
filters.Add("Orange");
filters.Add("Banana");
I have another list of strings, which contains sentences.
Example:
List<string> msgList = new List<string>();
msgList.Add("This sentence contains the word Apple.");
msgList.Add("This doesn't contain any fruits.");
msgList.Add("This does. It's a banana.");
Now I want to find out which items in msgList contains a fruit. For which, I use the following code:
foreach(string msg in msgList)
{
if(filters.Any(msg.Contains))
{
// Do something.
}
}
I'm wondering, is there a way in Linq where I can use something similar to List.Any() where I can check if msgList contains a fruit, and if it does, also get the fruit which matched the inquiry. If I can get the matching index in 'filters' that should be fine. That is, for the first iteration of the loop it should return 0 (index of 'Apple'), for the second iteration return null or something like a negative value, for the third iteration it should return 2 (index of 'Banana').
I checked around in SO as well as Google but couldn't find exactly what I'm looking for.
You want FirstOrDefault instead of Any.
FirstOrDefault will return the first object that matches, if found, or the default value (usually null) if not found.
You could use the List<T>.Find method:
foreach (string msg in msgList)
{
var fruit = filters.Find(msg.Contains);
if (fruit != null)
{
// Do something.
}
}
List<string> filters = new List<string>() { "Apple", "Orange", "Banana" };
string msg = "This sentence contains the word Apple.";
var fruit = Regex.Matches(msg, #"\w+", RegexOptions.IgnoreCase)
.Cast<Match>()
.Select(x=>x.Value)
.FirstOrDefault(s => filters.Contains(s));
A possible approach to return the indexes of the elements
foreach (string msg in msgList)
{
var found = filters.Select((x, i) => new {Key = x, Idx = i})
.FirstOrDefault(x => msg.Contains(x.Key));
Console.WriteLine(found?.Idx);
}
Note also that Contains is case sensitive, so the banana string is not matched against the Banana one. If you want a case insensitive you could use IndexOf with the StringComparison operator

In C # how to pass string.empty in a list of string

i have a list of string
Emails = new List<string>() { "R.Dun#domain.co.nz", "S.Dun#domain.co.nz" }
now i want to pass string.empty to first value of list
something like
policy.Emails = new List<string>(){string.Empty};
how to put a loop for e.g. for each value of list do something.
you can directly set the first element as string.Empty:
policy.Emails[0]=string.Empty;
You can use indexof function for finding a string in the list as below,
List<string> strList = new List<string>() { "R.Dun#domain.co.nz", "S.Dun#domain.co.nz" };
int fIndex = strList.IndexOf("R.Dun#domain.co.nz");
if(fIndex != -1)
strList[fIndex] = string.Empty;
Or if you want to replace first item with string.Empty then as dasblinkenlight mentioned you can do using the index directly,
strList[0] = string.Empty
Hope it helps.
You can prepend string.Empty to an existing list with concat:
var emails = new List<string> {"R.Dun#domain.co.nz", "S.Dun#domain.co.nz"};
policy.Emails = new[] {string.Empty}.Concat(emails).ToList();
Now policy.Emails looks like this:
{"", "R.Dun#domain.co.nz", "S.Dun#domain.co.nz"}
If you would like to replace the first item, use Skip(1) before concatenating:
policy.Emails = new[] {string.Empty}.Concat(emails.Skip(1)).ToList();
To generalize, replacing the initial n values with empty strings would look like this:
policy.Emails = Enumerable.Repeat(string.Empty, 1).Concat(emails.Skip(n)).ToList();
Note: It goes without saying that if you do not mind modifying the list in place, the simplest solution is to do
emails[0] = string.Empty;
If you want to add an empty string at the beginning of a list you could do:
emails.Insert(0, string.Empty);

Find substring in a list of strings

I have a list like so and I want to be able to search within this list for a substring coming from another string. Example:
List<string> list = new List<string>();
string srch = "There";
list.Add("1234 - Hello");
list.Add("4234 - There");
list.Add("2342 - World");
I want to search for "There" within my list and return "4234 - There". I've tried:
var mySearch = list.FindAll(S => s.substring(srch));
foreach(var temp in mySearch)
{
string result = temp;
}
With Linq, just retrieving the first result:
string result = list.FirstOrDefault(s => s.Contains(srch));
To do this w/o Linq (e.g. for earlier .NET version such as .NET 2.0) you can use List<T>'s FindAll method, which in this case would return all items in the list that contain the search term:
var resultList = list.FindAll(delegate(string s) { return s.Contains(srch); });
To return all th entries:
IEnumerable<string> result = list.Where(s => s.Contains(search));
Only the first one:
string result = list.FirstOrDefault(s => s.Contains(search));
What you've written causes the compile error
The best overloaded method match for 'string.Substring(int)' has some invalid arguments
Substring is used to get part of string using character position and/or length of the resultant string.
for example
srch.Substring(1, 3) returns the string "her"
As other have mentioned you should use Contains which tells you if one string occurs within another. If you wanted to know the actual position you'd use IndexOf
same problem i had to do.
You need this:
myList.Where(listStrinEntry => myString.IndexOf(listStringEntry) != -1)
Where:
myList is List<String> has the values
that myString has to contain at any position
So de facto you search if myString contains any of the entries from the list.
Hope this is what you wanted...
i like to use indexOf or contains
someString.IndexOf("this");
someString.Contains("this");
And for CaseSensitive use:
YourObj yourobj = list.FirstOrDefault(obj => obj.SomeString.ToLower().Contains("some substring"));
OR
YourObj yourobj = list.FirstOrDefault(obj => obj.SomeString.ToUpper().Contains("some substring"));

Categories