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.
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
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);
The following will select the name of a user who votes positively on an item and then put it in a comma separated string.
var string = string.Join(", ", comment.CommentVote.Where(v=> v.Vote == true).Select(v => v.User.FirstName).ToArray());
I want to be able to get the first and last name, put them together, and then list them out in a comma separated list.
Context: I am trying to create something similar to Facebook:
John Doe and 25 others like this
Where "25 others" provides a list of users on hover. I can loop through the users who voted and get the first and last names, concatenate them, and then add a comma, it just seems like there should be something simpler that lets me avoid the foreach loop.
Just concatenate them:
var str = string.Join(", ",
comment.CommentVote
.Where(v=> v.Vote)
.Select(v => v.User.LastName + " " + v.User.FirstName));
Besides you don't need to call ToArray() explicitly, as string.Join has an overload accepting IEnumerable<T>. And you cannot have a variable with the name string, as it's an alias for type System.String.
You can just join the to value you want in the select statement.
var results = string.Join(", ", comment.CommentVote.Where(v=> v.Vote)
.Select(v => string.Format("{0} {1}", v.User.FirstName, v.User.LastName)));
EDIT: Opps sorry, Konstantin Vasilcov already answered
I have a list of ints. When this list is
1,2,3
I wanted to create a string
'1|2|3'.
So, I did this
string valueIds = selectedAttributeValueIds.Aggregate("'", (current, valueId) => current + valueId + "|") + "'";
Problem is this gives
'1|2|3|'
How do I avoid getting that final '|' without resorting to writing an ugly bit of code to remove it if it exists?
Thanks,
Sachin
Instead of Aggregate use string.Join;
string valueIds = string.Join("|",listofInt);
where listofInt is your list of numbers.
EDIT: missed the part where single quote was added to the string. you can do:
string valuesIds = "'" + string.Join("|", listOfInt) + "'";
or
string valuesIds = string.Concat("'", string.Join("|", listOfInt), "'");
You can use string.Join for simpler:
var list = new[] {1, 2, 3};
var result = string.Format("'{0}'", string.Join("|", list));
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