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 Linq组元素的列表和计数值之和_C#_Linq_List_Sum_Aggregation - Fatal编程技术网

C# C Linq组元素的列表和计数值之和

C# C Linq组元素的列表和计数值之和,c#,linq,list,sum,aggregation,C#,Linq,List,Sum,Aggregation,我有一个对象列表,每个对象都包含一个字符串和一个浮点值 public class Element { public string Name; public float Value; public Element(string name,float value) { Name = name; Value = value; } } List<L

我有一个对象列表,每个对象都包含一个字符串和一个浮点值

 public class Element
    {

        public string Name;
        public float Value;

        public Element(string name,float value) {

            Name = name;
            Value = value;

        }

    }


    List<List<Element>> elementslist = new List<List<Element>>();

    elementslist.Add(new List<Element>() { new Element("Apple", 1.2f), new Element("Banana", 0) });
    elementslist.Add(new List<Element>() { new Element("Apple", 2.1f), new Element("Banana", 1.4f) });
    elementslist.Add(new List<Element>() { new Element("Apple", 0), new Element("Banana", 0) });
我需要按字符串值名称对这些元素进行分组,并按浮点值之和对组进行排序

 public class Element
    {

        public string Name;
        public float Value;

        public Element(string name,float value) {

            Name = name;
            Value = value;

        }

    }


    List<List<Element>> elementslist = new List<List<Element>>();

    elementslist.Add(new List<Element>() { new Element("Apple", 1.2f), new Element("Banana", 0) });
    elementslist.Add(new List<Element>() { new Element("Apple", 2.1f), new Element("Banana", 1.4f) });
    elementslist.Add(new List<Element>() { new Element("Apple", 0), new Element("Banana", 0) });
p、 有没有更聪明的聚合算法来获得这个结果?也许也可以考虑关闭这些值的列表顺序

非常感谢您

首先在列表中选择多个,然后按名称分组并按值之和排序:

var groups = elements.SelectMany(l => l)
                     .GroupBy(e => e.Name)
                     .OrderBy(g => g.Sum(x => x.Value))
这将为您提供一个IEnumerable,其中有一个元素的名称和Value成员中的值之和。希望能有帮助

elementslist.SelectMany(n => n).GroupBy(n => n.Name).Select(n => new Element(n.First().Name, n.Sum(p => p.Value))).OrderBy(n => n.Value)
或者按降序排列。
不妨为输出添加一个.Selectx=>new{Name=g.Key,Sum=g.Sumy=>y.Value}。@clakitect:是的,我想是这样,但问题不清楚,因为它说要对组进行排序,所以我把它放在了组中。谢谢,我需要一些关于Sum的语法:-clakitect谢谢你的插件-Arturo,你是正确的ABOT分组,如何访问可枚举以得到第二个结果?@ MykoCales:欢迎你,如果答案帮助你,请考虑它是被接受的。当然这是一个有效的答案,如何读取这个有序列表中的一个元素的名称和值?需要石膏吗?