how to get string from string list? - c#

I have list of string and there are number of string in the list.
Each string in the list start with number.
List<String> stringList=new List<String>();
stringList.Add("01Pramod");
stringList.Add("02Prakash");
stringList.Add("03Rakhi");
stringList.Add("04Test");
stringList.Add("04Test1");
stringList.Add("04Test2");
I want a Linq query that will return me list of string that starts with 04.

stringList.Where(s => s.StartsWith("04"))
or
stringList.Where(s => s.StartsWith("04")).ToList()
if you need a list

var result = stringList.Where(i => i.StartsWith("04"));

Here are the possible solution for it:
// Lambda
stringList.FindAll(o => o.StartsWith("04"));
// LINQ
(from i in stringList
where i.StartsWith("04")
select i).ToList();

I guess this will be easy to understand and its in proper format
var ss=from string g in stringList
where g.Substring(0,2)=="04"
select g;
foreach(string str in ss)
{
Console.WriteLine(str);
}

Related

Simply traditional foreach to Linq ForEach

I have a list of strings like:
abcd#domain.com
efgh#domain.com
ijkl#domain.com;mnop#domain.com;qrst#domain.com
uvwx#domain.com
yz#domain.com
I would like to want it as:
abcd#domain.com
efgh#domain.com
ijkl#domain.com
mnop#domain.com
qrst#domain.com
uvwx#domain.com
yz#domain.com
So I wrote the code below and it works as expected.
foreach (var email in emailAddressesOnRequest)
{
if (!string.IsNullOrEmpty(email) && email.Contains(';'))
{
emailAddressesOnRequest.AddRange(email.Split(';').ToList());
emailAddressesOnRequest.Remove(email);
}
}
Is there any way to simply it to LINQ ForEach?
What you are looking for is to iterate through the collection and for each item to return an item of a different kind. For that use Select.
Because in your case you possibly want to return from each item a collection of items, and don't want to have them in nested collections use SelectMany on the result of the Split(';') method.
List<string> values = new List<string>
{
"abcd#domain.com",
"efgh#domain.com",
null,
"ijkl#domain.com; mnop #domain.com; qrst #domain.com",
"uvwx#domain.com",
"yz#domain.com"
};
var result = values.Where(value => !string.IsNullOrWhiteSpace(value))
.SelectMany(value => value.Split(';')).ToList();
And in query syntax:
var result = (from value in values
where !string.IsNullOrWhiteSpace(value)
from email in value.Split(';')
select email).ToList();
var query = from line in emailAddressesOnRequest
where !String.IsNullOrEmpty(line)
from email in line.Split(';')
select email;
What helped me a lot to understand ling was The standard LINQ operators
If you split each string into substrings by semicolon, you get a collection of string sequences, or an IEnumerable<IEnumerable<string>>
The IEnumareable extension function to convert them to an IEnumerable<string> is Enumerable.SelectMany. When iterating over a SelectMany it is like you do a nested foreach:
List<string[]> listOfStringArrays = ...
List<string> outputList = new List<string>();
foreach (string[] stringArray in listOfStringArrays)
{
foreach (string str in stringArray)
{
outputList.Add(str);
}
}
In your example the inner foreach is done using AddRange.
Using Select and Split you convert your collection of strings to a sequence of string sequences. SelectMany will make it a sequence of strings:
IEnumerable<string> myInputStrings = ...
IEnumerable<string> outputStrings = inputStrings
.Select(inputString => inputString.Split(';'))
.SelectMany(splitResult => splitResult);
The Select will take each of the inputStrings, and split them by semicolon. The output is a string array, which implements IEnumerable<string>, even if your input didn't have a semicolon.
The SelectMany concatenates every string sequence of you sequence of string sequences. The result is one sequence of strings.
To convert to array or list use ToArray() or ToList().

List<comma-separated strings> => List<string>?

Trying to come up with a LINQy way to do this, but nothing's coming to me.
I have a List<> of objects which include a property which is a comma-separated list of alpha codes:
lst[0].codes = "AA,BB,DD"
lst[1].codes = "AA,DD,EE"
lst[2].codes = "GG,JJ"
I'd like a list of those codes, hopefully in the form of a List of strings:
result = AA,BB,DD,EE,GG,JJ
Thanks for any direction.
Use SelectMany to get all split codes and use Distinct to not repeat the values.
Try something like this:
var result = lst.SelectMany(x => x.codes.Split(",")).Distinct().ToList();
You need to use Split to split each string into multiple strings. Then you need to use SelectMany to concatenate multiple sequences into a single sequence, and then you need to use Distinct to remove duplicates.
var result =
lst
.SelectMany(x => x.codes.Split(','))
.Distinct()
.ToList();
if you need a string as a result:
string result = string.Join(",",lst.SelectMany(p=>p.codes.Split(",")).Distinct());
Try this:
List<string> list = new List<string>();
char[] sep = new char[1];
sep[0] = ',';
foreach (string item in lst)
{
list.AddRange(item.Split(sep));
}
list = list.Distinct().ToList();

Linq Query to Compare with List of string values

I need to compare and get the matching values from a string list with LINQ. Have a look at my code.
Code
Split = Id.Split(',');
List<string> uids = new List<string>(Split);
var model = (from xx in Db.ItemWeedLogs
where xx.ItemNo == uids
// I need to pass a string list to extract the matching record.
select xx).ToList();
Try this :
var model = (from xx in Db.ItemWeedLogs
where uids.Contains(xx.ItemNo)
select xx).ToList();
Try:
where uid.contains(xx.ItemNo)
I think this is much more faster and clear.
var model = Db.ItemWeedLogs
.Join(Id.Split(','), di => di.ItemNo, si => si, (d, s) => new {d})
.ToList();

Search for substring in an item of List

I have list :
List<string> str = new List<string>();
str.Add("asdf---US,IN");
str.Add("asdg---UK,IN");
str.Add("asjk---RU,IN");
str.Add("asrt---IT,DE");
I want to get List like ("asdf","asdg","asjk") when i enter "IN". For this i'm doing :
System.Text.RegularExpressions.Regex regEx =
new System.Text.RegularExpressions.Regex("asr",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
List<string> str = new List<string>();
str.Add("asdf---US,IN");
str.Add("asdg---UK,IN");
str.Add("asjk---RU,IN");
str.Add("asrt---IT,DE");
var getArray = str.Where<string>(item => regEx.IsMatch(item)).ToList<string>();
str = getArray.ToList();
str is having correct result. but it is containing whole item like "asdf---US,IN","asdg---UK,IN", "asjk---RU,IN". I only want first four character in item in list i.e., 'asdf", "asdg", "asjk". What condition can i put in lambda expression, to get list i want?
If its only going to be first four characters use string.SubString:
var getArray = str.Where(item => regEx.IsMatch(item))
.Select(r=> r.Substring(0,4))
.ToList();
You also doesn't need to specify <string> cast with where and ToList. Items in your list are already of type string.
EDIT:
If you are only looking for those strings that ends with "IN" you may get rid of the regex and use string.EndsWith:
var getArray = str.Where(item => item.EndsWith("IN"))
.Select(r=> r.Substring(0,4))
.ToList();
The regex should be
.*?(?=---.*?IN)
and the query should be
var getArray = str.Where<string>(item => regEx.IsMatch(item)).Select<string>(item => regEx.Match(item)).ToList<string>();

How can I convert comma separated string into a List<int> [duplicate]

This question already has answers here:
Convert comma separated string of ints to int array
(9 answers)
Closed 1 year ago.
string tags = "9,3,12,43,2"
List<int> TagIds = tags.Split(',');
This doesn't work cause the split method returns a string[]
Here is one way of doing it:
List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();
If you want to include some simple validation and skip over invalid values (instead of throwing an exception), here's something that uses TryParse:
string csv = "1,2,3,4,a,5";
int mos = 0;
var intList = csv.Split(',')
.Select(m => { int.TryParse(m, out mos); return mos; })
.Where(m => m != 0)
.ToList();
//returns a list with integers: 1, 2, 3, 4, 5
EDIT: Here is an updated query based on feedback by Antoine. It calls TryParse first to filter out any bad values, and then Parse to do the actual conversion.
string csv = "1,2,3,4,a,5,0,3,r,5";
int mos = 0;
var intList = csv.Split(',')
.Where(m => int.TryParse(m, out mos))
.Select(m => int.Parse(m))
.ToList();
//returns a list with integers: 1, 2, 3, 4, 5, 0, 3, 5
Edit 2: An updated query for C# 7.0, thanks to feedback from Charles Burns. Note that we get rid of the extra mos variable with this approach, so it's a bit cleaner.
string csv = "1,2,3,4,a,5,0,3,r,5";
var intList = csv.Split(',')
.Where(m => int.TryParse(m, out _))
.Select(m => int.Parse(m))
.ToList();
You can use LINQ w/ int.Parse() to convert the string[] to an IEnumerable<int> and then pass that result to the List<T> constructor:
var tagIds = new List<int>(tags.Split(',').Select(s => int.Parse(s)));
A little LINQ goes a long way:
List<int> TagIds = tags.Split(',')
.Select(t => int.Parse(t))
.ToList();
Without LINQ Query , you can choose this method ,
string tags = "9,3,12,43,2";
List<string> numbers = nos.Split(',').ToList<string>();
and then you can convert this List into integer type...
string tags = "9,3,12,43,2"
List<int> TagIds = tags.Split(',').Select(x => x.Trim()).Select(x=> Int32.Parse(x)).ToList();
If you are using C# 3.5 you can use Linq to achieve this
string tags = "9,3,12,43,2";
List<int> tagIds = tags.Split(',').Select(s=>int.Parse(s)).ToList();
or the short one
string tags = "9,3,12,43,2";
List<int> tagIds = tags.Split(',').Select(int.Parse).ToList();
string tags = "9,3,12,43,2";
List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();
I stumbled upon this and I just want to share my own solution without linq. This is a primitive approach. Non-integer values will not be added in the list also.
List<int> TagIds = new List<int>();
string[] split = tags.Split(',');
foreach (string item in split)
{
int val = 0;
if (int.TryParse(item, out val) == true)
{
TagIds.Add(val);
}
}
Hope this helps.
I made a modification to khalid13's answer. If the user put a string of "0", his answer would remove that from the resulting list. I did something similar but used an anonymous object.
var result = commaSeparatedString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => new { didConvert = int.TryParse(s.TrimNullProtection(), out convertedInt), convertedValue = convertedInt })
.Where(w => w.didConvert)
.Select(s => s.convertedValue)
.ToList();
TrimNullProtection is a custom function I made that protects if the string is null.
What the above does is strip out any strings that were not able to be converted with no error. If you need to error if there was a problem with the conversion, then the accepted answer should do the trick.
It's simple. First split the string.
Trim blank space present after comma(,).
Then use system defined ToList()
string inputText = "text1, text2"
To remove the space after ',' and convert this comma separated text to List
List<string> resultList = (inputText.Split(',')).Select(t => t).ToList();

Categories