I have a string that is like this:
Item1;Item2;Item3
but could also be
Item1
Is there a slick .net method to get that into a List?
string.split is your friend...
var yourString = "Item1;Item2;Item3";
var result = new List<string>(yourString.Split(';'));
LINQ has a way to bring the array to string, too:
var inputString = "item1;item2;item3";
var asList = inputString.Split( ';' ).ToList();
var input = "Item1;Item2;Item3";
var list = input.Split(new[] {";"}, StringSplitOptions.None).ToList();
Here's how I'd do that:
string[] arr = str.Split( new char[] { ';' } );
List<string> list = new List<string>( arr );
Related
I have some code as below:
char[] separator = { ',' };
String[] idList = m_idsFromRequest.Split(separator); //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().ToList();
m_distinctIdList = distinctIdList.ToArray();
m_idsFromRequest = string.Join(" ", distinctIdList);
currently m_idsFromRequest = ["1","2".........."] is as such.
I want to make it ["0|1","0|2".........."] like append "0|" in each element . I wanted to know id I could do it without the foreach loop.
You can use Select and String.Join:
var idsPrependedWithZero = m_idsFromRequest.Split(separator)
.Distinct() // same as in your code
.Select(id => $"0|{id}");
string result = string.Join(",", idsPrependedWithZero);
char[] separator = { ',' };
string m_idsFromRequest = "1,2,3,4,5,6";
String[] idList = m_idsFromRequest.Split(separator); //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().Select(t => "0|" + t).ToList();
m_idsFromRequest = string.Join(",", distinctIdList);
Just added the .Select() after .Distinct(). Inside the .Select you can transform each of the item in the list.
Apart from that i also added "," in your string.Join. Because you want it to be join by comma.
I have two strings consisting of several words (Comma separated). If string 1 consisting of words (; separated) which is to be ignored if it presents in string 2, below are the strings
var compToIgnore="Samsung,Motorola,Amazon";
var allCompanies="Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
var icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var c in listOfCompanies)
{
if (c.BrandId.StartsWith("A2"))
{
var item = allCompanies.Where(x => !icm.Contains(x));
var result = string.Join(",", item);
}
}
In result variable I wanted to have final result as "Godrej,Videocon,Huawei,Alibaba"
I don't see any proper result with above code
You can try Linq in order to query allCompanies:
using System.Linq;
...
var compToIgnore = "Samsung,Motorola,Amazon";
var allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
string result = string.Join(",", allCompanies
.Split(',')
.Except(compToIgnore.Split(',')));
Note, that Except removes all duplicates. If you want to preserve them, you can use HashSet<string> and Where instead of Except:
HashSet<string> exclude = new HashSet<string>(compToIgnore.Split(','));
string result = string.Join(",", allCompanies
.Split(',')
.Where(item => !exclude.Contains(item)));
Try following :
string compToIgnore = "Samsung,Motorola,Amazon";
string allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
string[] icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] ac = allCompanies.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string results = string.Join(",", ac.Where(x => !icm.Contains(x)));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a string and a string list. I am trying to return a list that whatever strList is contains in str, the result should be 4 and 21.
Here is my code, not sure what I am missing.
string str= "21,1,4";
List<string> strList= new List<string> { "4","21" };
var a = str.Where(i => i.ToString().Split(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries).ToList().Any(s=>strList.Contains(s)));
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
var splitStr = str.Split(',');
var result = splitStr.Where(x => strList.Contains(x));
string str= "21,1,4";
List<string> strList= new List<string> { "4","21" };
string[] result = str.Split(',');
foreach(string s in result)
if(strList.Contains(s))
Console.WriteLine(s);
Make it simple.
To keep it all on one line, which seems to be your goal:
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
var a = str.Split(',').Where(s => strList.Contains(s));
a will be an IEnumerable of all values in str (after splitting) that are contained in strList.
You can just use Intersect
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
var result = str.Split(',').Intersect(strList);
Console.WriteLine(string.Join(", ", result));
Output:
21, 4
The issue with your code is that by doing str.Where you are iterating over the characters of the string. You should instead just split str then iterate over that to find the matches in strList.
You can do
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
List<string> splitList = str.Split(",").ToList();
List<string> overlap = strList.Where(str => splitList.Contains(str)).ToList();
var str = "21,1,4";
var otherStrList = new List<string> { "4", "21" };
var separatedstrList = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
var commonStrings = separatedstrList.Intersect(otherStrList);
where commonStrings is the answer you're looking for.
How about an elegant Join syntax:
var results = (from main in str.Split(',')
join key in strList
on main equals key
select main).ToList();
you may add .Distinct() before .ToList() if you want to remove duplicates (if str has duplicates).
I'm learing the LINQ.
I made some codes.
string mySource = #"
#16
100%
Monitor
#19
98%
Guide
#77
0%
Cord
";
var myPattern = #"#(\d+)\r\n(\d+)%\r\n([^\r\n]*)\r\n";
var myCollection = Regex.Matches(mySource, myPattern, RegexOptions.Singleline)
.Cast<Match>().ToList();
MessageBox.Show(string.Join("\n", myCollection));
Looks nice.
But, What I really want to do is like this.
(this kind of data structure)
var myList = new List<string[]>();
var myArray1 = new string[] { "#16", "100%", "Monitor" };
var myArray2 = new string[] { "#19", "98%", "Guide" };
var myArray3 = new string[] { "#77", "0%", "Cord" };
myList.Add(myArray1);
myList.Add(myArray2);
myList.Add(myArray3);
What do I have to do ?
Regards
You can do:
List<string[]> myList = myCollection.Select(r => r.Value
.Split(new [] { '\r', '\n'},
StringSplitOptions.RemoveEmptyEntries)
).ToList();
You will end up with a List<T> with three elements, and each element would consists of array of strings.
I was not clear with my previous question
I have a list: new List<string> { "lts", "mts", "cwts", "rotc" };
Now I wan't to check a pattern in string that starts or ends with a forward slash like this: "cTws/Rotc/lTs" or "SomethingcTws cWtS/Rotc rOtc".
and convert to upper case only the string that starts/ends with a forward slash based on the list that I have.
So the output should be: "CWTS/ROTC/LTS", "SomethingcTws CWTS/ROTC rOtc"
I modified Sachin's answer:
List<string> replacementValues = new List<string>
{
"cwts",
"mts",
"rotc",
"lts"
};
string pattern = string.Format(#"\G({0})/?", string.Join("|", replacementValues.Select(x => Regex.Escape(x))));
Regex regExp = new Regex(pattern, RegexOptions.IgnoreCase);
string value = "Cwts/Rotc Somethingcwts1 Cwts/Rotc/lTs";
string result = regExp.Replace(value, s => s.Value.ToUpper());
Result: CWTS/ROTC Somethingcwts1 Cwts/Rotc/lTs
The desired output should be: CWTS/ROTC Somethingcwts1 CWTS/ROTC/LTS
So instead of using Regex, which I'm not really good with, I'm doing split by space then split by "/" then rejoin the strings
string val = "Somethingrotc1 cWts/rOtC/lTs Cwts";
List<string> replacementValues = new List<string>
{
"lts", "mts",
"cwts", "rotc"
};
string[] tokens = val.Split(new char[] { ' ' }, StringSplitOptions.None);
string result = string.Join(" ", tokens.Select(t =>
{
// Now split by "/"
string[] ts = t.Split(new char[] { '/' }, StringSplitOptions.None);
if (ts.Length > 1)
{
t = string.Join("/", ts.Select(x => replacementValues.Contains(x.ToLower()) ? x.ToUpper() : x));
}
return t;
}));
Output: Somethingrotc1 CWTS/ROTC/LTS Cwts
You want to change the specific words in the string to Upper case. Then you can use Regex to achieve it.
string value = "Somethingg1 Cwts/Rotc/Lts Cwts";
var replacementValues = new Dictionary<string, string>()
{
{"Cwts","CWTS"},
{"Rotc","ROTC"},
{"Lts","LTC"}
};
var regExpression = new Regex(String.Join("|", replacementValues.Keys.Select(x => Regex.Escape(x))));
var outputString = regExpression.Replace(value, s => replacementValues[s.Value]);