Linq:返回几列和列名的最大值

时间:2017-08-21 14:43:20

标签: wpf linq

我在WPF项目中有一个表,其中包含一些字符串列s1,s2,s3和几个数字列n1,n2,n3,n4。

在LINQ查询中,我需要选择行:

Dim query = From li in myList where li.s1="ok"

现在,我需要知道那些包含n1,n2,n3,4中最大值的列。这意味着结果应该是:

"The biggest value (4) is in column n2"

知道如何实现这一目标吗?

我找到了一些" FindMax"谷歌上的结果,但实际上他们从未提供列名称及其列索引...

2 个答案:

答案 0 :(得分:1)

首先,您需要像这样规范化数据:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.js"></script>
<div id="app"></div>

现在您可以轻松找到这样的最大值:

var norm = query.Select(q=>new { Column="n1", Value=q.n1 })
  .Concat(query.Select(q=>new { Column="n2", Value=q.n2 }))
  .Concat(query.Select(q=>new { Column="n3", Value=q.n3 }))
  .Concat(query.Select(q=>new { Column="n4", Value=q.n4 }));

输出:

var largest = norm
  .OrderByDescending(n=>n.Value)
  .First();

答案 1 :(得分:0)

试试这个:

var items = list.Where(x => x.S1 == "ok")
    .Select(x => new[] {
                    new { PropertyName = nameof(x.N1), Value = x.N1 },
                    new { PropertyName = nameof(x.N2), Value = x.N2 },
                    new { PropertyName = nameof(x.N3), Value = x.N3 },
                    new { PropertyName = nameof(x.N4), Value = x.N4 }}
        .OrderByDescending(y => y.Value)
        .First())
    .ToList();

foreach(var item in items)
{
    Console.WriteLine($"The biggest value ({item.Value}) is in column {item.PropertyName}.");
}

VB.NET版本:

Dim items = List _
    .Where(Function(x) x.S1 = "ok") _
    .Select(Function(x) {New With
    {
        Key .PropertyName = NameOf(x.N1),
        Key .Value = x.N1
    }, New With {
        Key .PropertyName = NameOf(x.N2),
        Key .Value = x.N2
    }, New With {
        Key .PropertyName = NameOf(x.N3),
        Key .Value = x.N3
    }, New With {
        Key .PropertyName = NameOf(x.N4),
        Key .Value = x.N4
    }}.OrderByDescending(Function(y) y.Value).First()) _
.ToList()