C# 获取不同的最大值
C# get distinct and max value
这是我的数据表
X Y P
Str1 C1 10
Str1 C1 5
Str1 C1 1
Str1 C1 2
Str2 C1 25
Str2 C1 4
Str1 C2 411
Str1 C2 2356
Str2 C2 12
Str2 C2 33
我正在尝试根据 X 和 Y 列获取不同的行,并使用 linq to dataset 获取 P 列的最大值
X Y P
Str1 C1 10
Str2 C1 25
Str1 C2 2356
Str2 C2 33
-
var query0 = (from row in tablo.AsEnumerable()
select new
{
X = row.Field<string>("X"),
Y = row.Field<string>("Y"),
}).Distinct();
我该怎么办?
谢谢
这里需要GroupBy
:-
var result = tablo.AsEnumerable().
.GroupBy(row => new
{
X= row.Field<string>("X"),
Y = row.Field<string>("Y")
})
.Select(x => new
{
X = x.Key.X,
Y = x.Key.Y,
P = x.Max(z => z.Field<int>("P"))
});
您可以尝试这样的操作:
var result = tablo.AsEnumerable()
.Select(row=> new
{
X = row.Field<string>("X"),
Y = row.Field<string>("Y"),
P = row.Filed<int>("P")
}).GroupBy(i=>new {X = i.X, Y = i.Y})
.Select(gr=>new{
X = gr.Key.X,
Y = gr.Key.Y
P = gr.Max(z => z.P)
});
本质上,我们首先声明一个匿名类型对象的序列,它具有三个属性,X
、Y
和P
。然后我们根据X
和Y
对这个序列进行分组。最后,我们取每组的最高价。
这是我的数据表
X Y P
Str1 C1 10
Str1 C1 5
Str1 C1 1
Str1 C1 2
Str2 C1 25
Str2 C1 4
Str1 C2 411
Str1 C2 2356
Str2 C2 12
Str2 C2 33
我正在尝试根据 X 和 Y 列获取不同的行,并使用 linq to dataset 获取 P 列的最大值
X Y P
Str1 C1 10
Str2 C1 25
Str1 C2 2356
Str2 C2 33
-
var query0 = (from row in tablo.AsEnumerable()
select new
{
X = row.Field<string>("X"),
Y = row.Field<string>("Y"),
}).Distinct();
我该怎么办? 谢谢
这里需要GroupBy
:-
var result = tablo.AsEnumerable().
.GroupBy(row => new
{
X= row.Field<string>("X"),
Y = row.Field<string>("Y")
})
.Select(x => new
{
X = x.Key.X,
Y = x.Key.Y,
P = x.Max(z => z.Field<int>("P"))
});
您可以尝试这样的操作:
var result = tablo.AsEnumerable()
.Select(row=> new
{
X = row.Field<string>("X"),
Y = row.Field<string>("Y"),
P = row.Filed<int>("P")
}).GroupBy(i=>new {X = i.X, Y = i.Y})
.Select(gr=>new{
X = gr.Key.X,
Y = gr.Key.Y
P = gr.Max(z => z.P)
});
本质上,我们首先声明一个匿名类型对象的序列,它具有三个属性,X
、Y
和P
。然后我们根据X
和Y
对这个序列进行分组。最后,我们取每组的最高价。