Aggregate Extension method and Final Character removal - c#

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

Related

LINQ query stores values in KeyValuePair<string, string> list but then cannot store them all with addrange

The following LINQ query gets all parameters for all stations , every station (x.station) has X parameters (x.parameters) and I need all of them for both 'Result' and 'Values'. It might be a bit confusing at first since this line:
from x in selection.Parameters
represents x stations, not x parameters.
LINQ query:
var selectionData =
from x in selection.Parameters
select new
{
Result = "(p.col_IdEstacion = " + x.Station + " and p.col_Sigla in(" +
("'" + string.Join("','", x.Parameters) + "'") + "))",
Values =
(
from y in x.Parameters
select new KeyValuePair<string, string>(
x.Station.ToString(), y)).ToList()
};
the reason why I'm doing this is because i want to store all parameters in all stations stored in 'Values' later on in a KeyValuePair List:
List<KeyValuePair<string, string>> myList
UPDATED: found out the code is working , what im doing wrong is to add 'Values' to the list, it might be the FirstOrDefault() that takes only the first one:
values.AddRange(selectionData.Select(d => d.Values).FirstOrDefault());
ANSWER: found out the correct way to store all values retrieved with LINQ is using SelectMany like this:
valores.AddRange(selectionData.SelectMany(d => d.Values))
Thanks
You could try it with
ToDictionary instead
But as i dont speak this kind of linq, i only work with the method chaining, i'm not sure if this will compile, but maybe it is a hint for you what to try.
var selectionData =
from x in selection.Parameters
select new
{
Result = "(p.col_IdEstacion = " + x.Station + " and p.col_Sigla in(" +
("'" + string.Join("','", x.Parameters) + "'") + "))",
Values = x.Parameters.ToDictionary(k=>k.Station.ToString(), v=>v)
};
ANSWER: found out the correct way to store all values retrieved with LINQ is using SelectMany like this:
valores.AddRange(selectionData.SelectMany(d => d.Values))

Concatenate string from array and include it's index C#

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.

Add comma between values by using Linq

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

How to remove a part of string effectively

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

Removing duplicates from Array with C#.NET 4.0 LINQ?

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

Categories

Resources