开发者

how to group many rows into one row?

开发者 https://www.devze.com 2023-03-23 08:37 出处:网络
I got something like this: int, string ------------ 1, \'test1\' 1, \'test2\' 2, \'test1\' 2, \'test2\' 2, \'test3\'

I got something like this:

   int, string
   ------------
    1, 'test1'
    1, 'test2'
    2, 'test1'
    2, 'test2'
    2, 'test3'
    3, 'test1'
    4, 'test1'
    4, 'test2'

I want to transform this into

   int, string
   ------------
开发者_StackOverflow中文版    1, 'test1, test2'
    2, 'test1, test2, test3'
    3, 'test1'
    4, 'test1, test2'

I tried many thing, like GroupBy with SelectMany but it's giving me runtime errors


This worked for me:

var list = new List<KeyValuePair<int, string>>() {
           new KeyValuePair<int, string>(1, "test1"),
           new KeyValuePair<int, string>(1, "test2"),
           new KeyValuePair<int, string>(2, "test1"),
           new KeyValuePair<int, string>(2, "test2"),
           new KeyValuePair<int, string>(2, "test3"),
           new KeyValuePair<int, string>(3, "test1"),
           new KeyValuePair<int, string>(4, "test1"),
           new KeyValuePair<int, string>(4, "test2"),
        };

        var result = (from i in list
                      group i by i.Key into g
                      select new
                      {
                          Key = g.Key,
                          Values = string.Join(", ", (from k in g
                                                      select k.Value))
                      });

        foreach (var x in result)
        {
            Console.WriteLine(x.Key + " - " + x.Values);
        }


If your type is:

class Foo
{
   public int MyInt { get; set;}
   public string MyString { get; set; }
}

Then your query would be something like:

IEnumerable<Foo> foos = ..    
var output = foos.GroupBy(foo => foo.MyInt, foo => foo.MyString);

I assume you don't need to concatenate the strings within a group together (since you mentioned SelectMany).


I have no clue what your object structure looks like but the following should get you on your way.

var rawData = new []
{
    new { Id = 1, Description = "test1" },
    new { Id = 1, Description = "test2" },
    new { Id = 2, Description = "test3" },
    new { Id = 2, Description = "test4" },
    new { Id = 3, Description = "test4" },
};

var result = from data in rawData
    group data by data.Id into g
select new { g.Key, Descriptions = string.Join(",", g.Select(i => i.Description)) };

result.Dump();

You can test those statements using LinqPad (http://www.linqpad.net)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号