C# 如何查找行中的最高值并返回列标题及其';s值

C# 如何查找行中的最高值并返回列标题及其';s值,c#,sql,database,entity-framework,linq,C#,Sql,Database,Entity Framework,Linq,假设在实体框架数据库中有一行5个数值,如何检索该行的前2列,包括列的名称及其值?最好使用LINQ 例如: a b c d e 0 4 5 9 2 前两个值分别为9和5。我想检索值和列名c和d 一个更实际的例子: var row = table.Where(model => model.Title.Contains(a.Title)); 这一行将给我一个包含许多数值的单行。 我想要如下的东西 row.list().OrderByDescendingOrder().top(

假设在实体框架数据库中有一行5个数值,如何检索该行的前2列,包括列的名称及其值?最好使用LINQ

例如:

a  b  c  d  e
0  4  5  9  2
前两个值分别为9和5。我想检索值和列名c和d

一个更实际的例子:

var row = table.Where(model => model.Title.Contains(a.Title));
这一行将给我一个包含许多数值的单行。 我想要如下的东西

row.list().OrderByDescendingOrder().top(2);

我不知道您在linq中是如何做到这一点的,但这里有一个SQL Server查询:

select t.*, v2.*
from t cross apply
     (values ('a', a), ('b', b), ('c', c), ('d', d), ('e', e)
     ) v(col, val) cross apply
     (select max(case when seqnum = 1 then val end) as val1,
             max(case when seqnum = 1 then col end) as col1,
             max(case when seqnum = 2 then val end) as val2,
             max(case when seqnum = 3 then col end) as col2
      from (select v.*, row_number() over (order by val desc) as seqnum
            from v
           ) v
     ) v2;
编辑:

当然,您可以使用大量的
case
表达式来获得最大值:

select t.*,
       (case when a >= b and a >= c and a >= d and a >= e then a
             when b >= c and b >= d and b >= e then b
             when c >= d and c >= e then c
             when d >= e then d
             else e
        end) as max_value,
       (case when a >= b and a >= c and a >= d and a >= e then 'a'
             when b >= c and b >= d and b >= e then 'b'
             when c >= d and c >= e then 'c'
             when d >= e then 'd'
             else 'e'
        end) as max_value_col          
from t;
问题是将其扩展到第二个值,特别是在存在重复值的情况下。

看起来您希望删除此数据,但使用Linq而不是T-SQL。(或其他一些SQL方言)

实现这一点的基本模式是使用 一个键/值对数组,可以对其执行降序操作

下面是一个比较通用的模式:

// The values that we want to query.
// In your case, it's essentially the table that you're querying.
// I used an anonymous class for brevity.
var values = new[] {
    new { key = 99, a = 0, b = 4, c = 5, d = 9, e = 2 },
    new { key = 100, a = 0, b = 5, c = 3, d = 2, e = 10 }
};

// The query. I prefer to use the linq query syntax
// for actual SQL queries, but you should be able to translate
// this to the lambda format fairly easily.
var query = (from v in values
            // Transform each value in the object/row
            // to a name/value pair We include the key so that we
            // can distinguish different rows.
            // Because we need this query to be translated to SQL,
            // we have to use an anonymous class.
            from column in new[] { 
                new { key = v.key, name = "a", value= v.a },
                new { key = v.key, name = "b", value= v.b },
                new { key = v.key, name = "c", value= v.c },
                new { key = v.key, name = "d", value= v.d },
                new { key = v.key, name = "e", value= v.e }
            }

            // Group the same row values together
            group column by column.key into g

            // Inner select to grab the top two values from
            // each row
            let top2 = (
                from value in g
                orderby value.value descending
                select value
            ).Take(2)

            // Grab the results from the inner select
            // as a single-dimensional array
            from topValue in top2
            select topValue);

// Collapse the query to actual values.
var results = query.ToArray();

foreach(var value in results) {
    Console.WriteLine("Key: {0}, Name: {1}, Value: {2}", 
        value.key, 
        value.name, 
        value.value);
}
但是,由于只有一行,逻辑变得简单得多:

// The value that was queried
var value = new { key = 99, a = 0, b = 4, c = 5, d = 9, e = 2 };

// Build a list of columns and their corresponding values.
// You could even use reflection to build this list.
// Additionally, you could use C# 7 tuples if you prefer.
var columns = new[] { 
    new { name = "a", value = value.a },
    new { name = "b", value = value.b },
    new { name = "c", value = value.c },
    new { name = "d", value = value.d },
    new { name = "e", value = value.e }
};

// Order the list by value descending, and take the first 2.
var top2 = columns.OrderByDescending(v => v.value).Take(2).ToArray();

foreach(var result in top2) {
    Console.WriteLine("Column: {0}, Value: {1}", result.name, result.value);
}

因此,您有一个项集合,可以根据其一个属性进行排序,并且希望集合中的两个项具有此排序属性的最大值

var result = myItems
    .OrderByDescending(myItem => myItem.MyProperty)
    .Take(2);
换句话说:按MyProperty的降序排列整个集合,并从结果中获取前两项,这两项将是MyProperty值最大的两项

这将返回两个完整的myItem对象。通常情况下,将更多的属性从对象传输到本地内存并不是一个好主意。使用Select可确保仅传输您计划使用的值:

var bestSellingProducts = products
    .OrderByDescending(product=> product.Orders.Count())
    .Select(product => new
    {   // select only the properties you plan to use, for instance
        Id = product.Id,
        Name = product.Name,
        Stock = product.Stock
        Price = product.Price,
    });
    .Take(2);

用你正在使用的数据库标记你的问题。嗨,谢谢你的建议。我试图应用此查询,但没有成功。有没有更简单的方法来检索行中具有最高值的列?@Darius。问题的起因是什么?我想我可能在过去的10个小时里一直坐在同一个位置试图解决这个问题,现在我应用了你的建议,我相信你已经解决了。非常感谢你!把它标记为一个答案!