我有一个数据表(有2列):
X Y
AA 100
BB 150
AA 25
BB 10
CC 120
正如您所见:
AA值总和为125
BB值总和为160
CC值总和为120
BB
的最大总和 160我想获得这个值,即和的最大值,其中sum是grup的值,按X列值分组,还有X值。
如何在VB.NET中使用LINQ执行此操作?
谢谢!
编辑: 这是我正在使用的代码:
Dim marfa = _
From dr In dtMarfuriT _
Group dr By Key = dr("MRF_COD") Into Group _
Let maxim = Group.Sum(Function(dr) dr("MRF_MASA_STABILITA")) _
Select New With { _
Key .cod = Key, _
Key .TopMarfa = Group.First(Function(dr) Group.Sum(Function(drx) CDbl(drx("MRF_MASA_STABILITA"))) = maxim)("MRF_COD"), _
Key .Maximul = maxim}
Dim MasaMaxima As Double = marfa.Maximul
Dim CodulMaseiMaxime As String = marfa.TopMarfa
答案 0 :(得分:2)
B a1 = new B() { Text = "AA", Number = 100};
B a2 = new B() { Text = "BB", Number = 150};
B a3 = new B() { Text = "AA", Number = 25};
B a4 = new B() { Text = "BB", Number = 10};
B a5 = new B() { Text = "CC", Number = 120};
List<B> list = new List<B>();
list.Add(a1);
list.Add(a2);
list.Add(a3);
list.Add(a4);
list.Add(a5);
var l = from i in list
group i by i.Text into g
let sum = g.Sum(e=>e.Number)
orderby sum descending
select new
{
Text = g.Key,
Sum = sum
};
var item = l.First();
Console.WriteLine(item.Sum);
public class B
{
public int Number{get;set;}
public string Text{get;set;}
}
答案 1 :(得分:0)
这是C#中的示例
// sample array
Tuple<string, int>[] arr = new Tuple<string, int>[]
{
new Tuple<string, int>("AA", 10),
new Tuple<string, int>("AA", 20),
new Tuple<string, int>("BB", 10),
new Tuple<string, int>("BB", 60)
};
// calcs
var result = arr.GroupBy(a => a.Item1)
.Select(g => new {Key = g.Key, S = g.Select(s => s.Item2).Sum()})
.OrderByDescending(g => g.S)
.FirstOrDefault();
// or
var result1 =
(from tuple in arr
group tuple by tuple.Item1 into gr
let s = gr.Select(s => s.Item2).Sum()
orderby s descending
select new {x = gr, y = s}).FirstOrDefault();
答案 2 :(得分:0)
Dim result= _
(From dr In dtX _
Group dr By Key = dr("A") Into Group _
Select New With { _
Key .Code = Key, _
SumX = Group.Select(Function(drx) CDbl(drx("B"))).SumX}) _
.OrderByDescending(Function(g) g.SumX).FirstOrDefault
Dim MaxSumX As Double = result.SumX
Dim MaxCode As String = result.Code