My values come from ComboBox:
2|722|742|762|77
I delete unnecessary characters as follows:
foreach (var item in checkListBox)
{
string[] list = item.Split(
new string[] { "2|" },
StringSplitOptions.RemoveEmptyEntries);
}
My list values result:
"72"
"74"
"76"
"77"
My question is:
how can I get all of the above values in 1 row (next to each other) separated by comma like this:
72,74,76,77
?
It sounds like you just want string.Join:
string commaSeparated = string.Join(",", list);
(Note that this is not part of LINQ - it's not the same kind of "join" as for joining multiple sequences. It's joining several strings together with a separator.)
While you can do this in a single statement as per the currently accepted answer, I'd personally consider leaving your existing statement and having this as a separate step. It makes the code easier to both read and debug.
String.Join(",",list);
Though: a) This is not Linq. b) As is mentioned in another answer here - It would be simpler in this case to use Replace.
Using Linq:
list.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(',');
How about
var result = string.Join(",", item.Split(new string[] { "2|" }, StringSplitOptions.RemoveEmptyEntries));
Just use Replace directly:
string input = "2|722|742|762|77";
var result = input.Replace("2|",",").Trim(',');
As noted in the other answers, string.Join is what should be used here. If you'd however insist on LINQ:
var result = list
.Skip(1)
.Aggregate(
list.FirstOrDefault() ?? string.Empty,
(total, current) => total + "," + current);
Related
Please help on converting a list of objects got from DB into substrings separated by a comma
Take for example I have a sample code below:
List<string> CategoryNames = new List<string>();
CategoryNames.Add("myName1");
CategoryNames.Add("myName2");
CategoryNames.Add("myName3");
I want to convert CategoryNames into a format like this
"myName1","myName2","myName3"
From the above CatgoryNames happen to be retrieved from db.
var categoryNames = _context.BillingCategory.ToList();
How do I convert the categoryNames into substrings as shown above?
Any help will be appreciated.
You can use String.Join() method by combining with LINQ for preserving the quotes before joining:
var result = String.Join(",", CategoryNames.Select(item => $"\"{item}\""));
And here is the clearer version of the code if you don't linke singleliner:
var QuotedCategroyNames = CategoryNames
.Select(item => $"\"{item}\"");
var result = String.Join(",", QuotedCategroyNames);
Use LINQ Select to enclose all names in quotes, then string.Join to merge back into a comma separated string.
string.Join(',', CategoryNames.Select(n => '"' + n + '"'));
You can use string.Join() and concat with the double quotes character :
var serialized = $#"""{ string.Join(#""",""", CategoryNames) }"""; // "myName1","myName2","myName3"
Try it yourself
Consider the following csv
string data = "Hey, Bob, How are you";
I can flatten it to:
"Hey; Bob; How are you"
Using the following:
var s = String.Join("; ",data.Split(',').Select(d => d.Trim()).ToArray());
Is there any way I can get the index of the current item in the join and append it to the resulting string? To produce somthing along the lines of:
"Hey=0; Bob=1; How are you=2"
Does linq facilitate anything like this? Perhaps combined with a String.Format() type method?
Here try this there is an index selector in the select you can use it to concatonate with each of your data pieces
var s = String.Join("; ",data.Split(',')
.Select((d, i) => d.Trim() + "= " + i.ToString()).ToArray());
Sure - just change your Select slightly:
var s = String.Join("; ",data.Split(',')
.Select((d, i) => String.Format("{0}={1}",d.Trim(),i)));
note that string.Join can take an IEnumerable<T> so there's no need to call ToArray.
I have an array of words
string[] words = { "believe", "relief", "receipt", "field" };
How to find out the words with the substring "ei" using linq
IEnumerable<string> iswordlist = from word in words where words.All(a => a.Contains("ei"))
select word;
foreach (var i in iswordlist)
{
txtlinq.Text = txtlinq.Text + i.ToString();
}
I tried the above but got no result. Can anyone help me on this?
Try like this
var newWord = words.Where(o => o.Contains("ei"));
I'm not very good with free form, but with dot syntax this will work:
var ieWords = words.Where(a => a.Contains("ei"));
Your current code won't even compile because you are using Enumarbale.All method which returns either true or false (when given condition matches) and not an IEnumerable on which you can query. You simple need a Where clause.
Try this:-
var result = words.Where(x => x.Contains("ei"));
Or if you prefer query syntax:-
IEnumerable<string> result = from word in words
where word.Contains("ei")
select word;
Working Fiddle.
Have a string like A=B&C=D&E=F, how to remove C=D part and get the string like A=B&E=F?
Either just replace it away:
input.Replace("&C=D", "");
or use one of the solutions form your previous question, remove it from the data structure and join it back together.
Using my code:
var input = "A=B&C=D&E=F";
var output = input
.Split(new string[] {"&"}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=', 2))
.ToDictionary(d => d[0], d => d[1]);
output.Remove("C");
output.Select(kvp => kvp.Key + "=" + kvp.Value)
.Aggregate("", (s, t) => s + t + "&").TrimRight("&");
using System.Web; // for HttpUtility
NameValueCollection values = HttpUtility.ParseQueryString("A=B&C=D&E=F");
values.Remove("C");
values.ToString(); // "A=B&E=F"
I think you need to give a clearer example to make sure it's something for the situation, but something like this should do that:
var testString = "A=B&C=D&E=F"
var stringArray = testString.Split('&');
stringArray.Remove("C=D");
var output = String.Join("&", stringArray);
Something like that should work, and should be pretty dynamic
You can either split() and manually join (depending how the data looks like) or simly use string.Replace(,string.empty)
Split it on the & separator, exclude the C=D part by some mechanism, then join the remaining two? The String class provides the methods you'd need for that, including splitting, joining and substring matching.
string xyz = "A=B&C=D&E=F";
string output = xyz.Replace("&C=D","");
Output: A=B&E=F
I have this c# code that builds a string of comma seperated matches for a service:
for (m = r.Match(site); m.Success; m = m.NextMatch())
{
found = found + "," + m.Value.Replace(",", "");
}
return found;
Output looks like: aaa,bbb,ccc,aaa,111,111,ccc
Now that code is on .NET 4.0 How can I use C# LINQ to remove duplicates?
Also, Any way to remove duplicates without changing order?
I found this sample code in another post, but not sure exactly how to apply it:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
Thanks.
string[] s = found.Split(',').Distinct().ToArray()
Rewrite the code that builds the result to output it directly.
ie. rewrite this:
for (m = r.Match(site); m.Success; m = m.NextMatch())
{
found = found + "," + m.Value.Replace(",", "");
}
return found;
To this:
return (from Match m in r.Matches(site)
select m.Value.Replace(",", "")).Distinct().ToArray();
This will return an array. If you still want it back as a string:
return string.Join(", ", (from Match m in r.Matches(site)
select m.Value.Replace(",", "")).Distinct().ToArray());
You may or may not be able to remove the last .ToArray() from the last code there depending on the .NET runtime version. .NET 4.0 string.Join(...) can take an IEnumerable<string>, whereas previous versions requires an array.
This will return a string of comma seperated values without duplicates:
var result = string.Join(",",
r.Matches(site)
.Cast<Match>()
.Select(m => m.Value.Replace(",", string.Empty))
.Distinct()
);
this could be one possible solution:
var data = new List<string>();
for (m = r.Match(site); m.Success; m = m.NextMatch())
data.Add(m.Value.Replace(",", ""));
return String.Join(",", data.Distinct().ToArray());
You can achieve this in a single LINQ query
string strSentence = "aaa,bbb,ccc,aaa,111,111,ccc";
List<string> results = (from w in strSentence.Split(',') select w).Distinct().ToList();