Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach while a value is same as previous value

Tags:

c#

linq

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);
    }
like image 253
Dave Avatar asked Feb 18 '26 06:02

Dave


1 Answers

List<string> result = myTuple.GroupBy(t => t.Item1)
                     .Select(g => String.Join(" ", g.Select(tp=>tp.Item2)))
                     .ToList();
like image 185
L.B Avatar answered Feb 20 '26 19:02

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!