在列表<列表<字符串>上的Linq(GroupBy和Sum). [英] Linq (GroupBy and Sum) over List<List<string>>

查看:57
本文介绍了在列表<列表<字符串>上的Linq(GroupBy和Sum).的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构:

List<List<string>> content

基本上,这是逗号分隔文件中的内容.列表中的第一个元素将是代表标题的字符串列表.列表中的所有其他元素将是代表值的字符串列表.

This is bascially the content from a comma seperated file. The first element in the list will be a list of strings representing the headers. All other element in the list will be a list of strings representing the values.

我正在尝试运行如下查询.其中代码"和书"是两个标题,我需要将它们按2分组,然后按另一个标题求和.这是我的尝试,但是我当然不能直接在内容上使用Groupby,因为它是一个列表列表.

I am trying to run a query like below. Where "code" and "book" are two headers and I need to group by them 2 and sum by another header. This is my attemp but of course I cannot use the Groupby on the content directly as it is a list of lists.

List<List<string>> content = MyContent();

var linqResults = content
                  .GroupBy(x => new { Code = x["code"], Book = x["book"] })
                  .Select(g =>
                   {
                       return new
                       {
                           Book = g.Key.Book,
                           Code = g.Key.Code,
                           Total = g.SelectMany(x => x["columnToSum"].Sum())
                       };
                   });

推荐答案

我同意Sergey的评论,但是您可以执行以下操作:

I agree with Sergey's comment but You could do something like this:

var content = new List<List<string>>
        {
            new List<string>{ "book", "code", "columnToSum" },
            new List<string>{ "abc", "1", "10" },
            new List<string>{ "abc", "1", "5" },
            new List<string>{ "cde", "1", "6" },
        };

var headers = content.First();
var result = content.Skip(1)
    .GroupBy(s => new { Code = s[headers.IndexOf("code")], Book = s[headers.IndexOf("book")]})
    .Select(g => new
             {
                 Book = g.Key.Book,
                 Code = g.Key.Code,
                 Total = g.Select(s => int.Parse(s[headers.IndexOf("columnToSum")])).Sum()
             });

哪个返回:

{ Book = abc, Code = 1, Total = 15 }
{ Book = cde, Code = 1, Total = 6 }

这篇关于在列表&lt;列表&lt;字符串&gt;上的Linq(GroupBy和Sum).的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆