Compare list of string with string in linq - c#

I have list of string
Like list1 contain 'pinky','smita','Rashmi','Srivani'
And string is like
String str = "pinky, Nandini'
I want to check if neither of str present in list1,proceed further.
how to do that?

If I understood correctly, you want to return false in the example case, so you can use Any method: Check if none of the elements of the list is already in the str, here is a one liner:
if (!list.Any(x=>str.Contains(x))) ....

You can use combination of .Any() with .Contains() with !,
var list1 = new List<string>(){ "pinky", "smita", "Rashmi", "Srivani" };
string str = "pinky, Nandini";
var list2 = str.Split(",");
var nameExists = list2.Any(x => list1.Contains(x));
if(!nameExists)
{
//Your code goes here.
}
As #Fildor said, you can use Intersect(). Elegant approach,
//All credit goes to #Fildor
var nameExists = list1.Intersect(list2).Any();

Related

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);

compare list of strings with another string

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.

How to remove a specific string from list<strings>

I've got a list of strings called xyz the string has this structure iii//abcd, iii//efg. how can I loop through this list and remove only iii// ?
I have tried this but it remove everything. thanks
string mystring = "iii//";
xyz.RemoveAll(x=> x.Split ('//')[0].ToString().Equals (mystring));
Removing all the strings who start with iii//:
xyz.RemoveAll(x => x.StartsWith(#"iii//"));
Removing the iii// from all strings:
var newList = xyz.Select(x => x.Replace(#"iii//", string.Empty)).ToList();
You can try this also which will remove the string from list if it starts with "iii/" other wise not.
string mystring = "iii//";
xyz.RemoveAll(x=>x.StartsWith(mystring));
I believe OP wants something to remove iii// from all strings:
string prefix = "iii///";
List<string> xyz = ...;
var result = xyz.Select(x => x.Substring(prefix.Length)).ToList();
Note: this of course assumes that each string really starts with prefix.

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"));

The ForEach Replace on this small code doesn't do what I expected it to do. What am I doing wrong here?

I don't know if this is LINQPad-related or I'm doing something wrong, but this code doesn't do what I want it to do, specifically the ForEach(...)
My goal is to replace the " " with an empty string; is there a better way to do this?
var lastNames = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN";
var listLastNames = lastNames.Split(',');
var list = listLastNames.ToList(); //so I can use .ForEach
list.ForEach(i=>i.Replace(" ",String.Empty));
list.Dump(); //show it on output
As others have pointed out, strings are immutable. Calling Replace simply returns a new string; it does not mutate the existing string in place. Here are three ways to do what you want:
Do the transformation on the sequence, and convert it to a list at the end:
string s = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN";
List<string> lastNames = s.Split(',').Select(x=>x.Trim()).ToList();
Or, the same thing in query syntax:
string s = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN";
var query = from lastName in s.Split(',')
select lastName.Trim();
List<string> lastNames = query.ToList();
Or, make an array and mutate the array in place:
string s = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN";
string[] lastNames = s.Split(',');
for (int i = 0; i < lastNames.Length; ++i)
lastNames[i] = lastNames[i].Trim();
Replace returns a new value, but doesn't affect the original String that you call it on. To do what you need, you'd have to build a new collection with the results from Replace - you can do this easily with Select:
var replaced = list.Select(i=>i.Replace(" ",String.Empty));
Another benefit, you won't need to cast to a List<T> to do this.
And as others have pointed out, you can use Trim() as a cleaner solution than Replace():
var collection = lastNames.Split(',').Select(i => i.Trim());

Categories