I'm finding it hard to explain this question, but I think it's a common problem many of us have come across.
Assume I have a List<string, string>
in the following format:
1, value-
1, and value-
1, again value-
2, another value-
2, yet another value-
I'd like to convert this into List<string>
which would have only contain 2 items
value-and value-again value-
another value-yet another value
This is based upon the number (1 or 2).
The code I typically use works, but seems some what cumbersome.
Is there a neater way, possibly with Linq?
A quick console app to demonstrate what I'm trying to do which hopefully explains it better than my question!
class Program
{
static void Main(string[] args)
{
List<Tuple<string, string>> myTuple = new List<Tuple<string, string>>();
myTuple.Add(new Tuple<string, string>("1", "value-"));
myTuple.Add(new Tuple<string, string>("1", "and value-"));
myTuple.Add(new Tuple<string, string>("1", "again value-"));
myTuple.Add(new Tuple<string, string>("2", "another value-"));
myTuple.Add(new Tuple<string, string>("2", "yet another value"));
string previousValue = "";
string concatString = "";
List<string> result = new List<string>();
foreach (var item in myTuple)
{
if (string.IsNullOrEmpty(previousValue))
previousValue += item.Item1;
if (previousValue == item.Item1)
concatString += item.Item2;
else
{
result.Add(concatString);
concatString = "";
previousValue = item.Item1;
concatString=item.Item2;
}
}
//add the last value
result.Add(concatString);
}