Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用C语言对列表进行分组和求和#_C#_Linq - Fatal编程技术网

C# 用C语言对列表进行分组和求和#

C# 用C语言对列表进行分组和求和#,c#,linq,C#,Linq,我有一张C#g.的清单 我想在列表中返回结果,如下所示: A,5 B,7 C,3 因此,按第一列分组,并对第二列求和 我该怎么做?很高兴使用LINQ。声明和代码如下: class Program { static void Main(string[] args) { List<MyList> list = new List<MyList>(); list.Add(new MyList() { Letter = "A",

我有一张C#g.的清单

我想在列表中返回结果,如下所示:

A,5
B,7
C,3
因此,按第一列分组,并对第二列求和

我该怎么做?很高兴使用LINQ。声明和代码如下:

class Program
{
    static void Main(string[] args)
    {
        List<MyList> list = new List<MyList>();

        list.Add(new MyList() { Letter = "A", Value = 1 });
        list.Add(new MyList() { Letter = "B", Value = 2 });
        etc... 
    }
}

class MyList
{
    public string Letter { get; set; }
    public long Value { get; set; }
}
类程序
{
静态void Main(字符串[]参数)
{
列表=新列表();
添加(new MyList(){Letter=“A”,Value=1});
添加(new MyList(){Letter=“B”,Value=2});
等
}
}
类MyList
{
公共字符串字母{get;set;}
公共长值{get;set;}
}
听起来你想要:

var results = list.GroupBy(x => x.Letter, x => x.Value)
                  .Select(g => new { Letter = g.Key, Sum = g.Sum() });
(不清楚您的类型,但希望您能从中获得所需的列表。)

有一个超负荷的
GroupBy
,它可以让您在一个调用中完成所有这些,但我个人觉得上面的版本更简单

var results = data.GroupBy(item => item.Letter)
.Select(group => new
{
  Letter = group.Key,
  Count = group.Sum(item => item.Value),
});

只需将
Letter
替换为给你“A”、“B”、“C”等的任何属性,将
Value
替换为给你1、2、3等的任何属性。如果
A、1
是一个字符串,而不是一个有两个属性的类,那么你需要解析该字符串。

列表是二维的吗?像一个
列表
?您想要一个只使用LINQ的解决方案吗?因为除此之外,解决方案是微不足道的..我在C#中有一个列表-然后至少发布声明。
var results = data.GroupBy(item => item.Letter)
.Select(group => new
{
  Letter = group.Key,
  Count = group.Sum(item => item.Value),
});