如何在一行中找到最高价值并返回列标题及其值

时间:2018-02-18 21:05:02

标签: c# sql database entity-framework linq

想象一下Entity Framework数据库中的一行5个数值,我如何检索该行的前2列,包括列的名称及其值?最好使用LINQ。

例如:

a  b  c  d  e
0  4  5  9  2

前2个值是9和5.我想检索值和列名称c和d。

更实际的例子:

var row = table.Where(model => model.Title.Contains(a.Title));

这一行会给我一行包含许多数值。 我想要的东西如下,

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

3 个答案:

答案 0 :(得分:0)

我不知道如何在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;

问题是将此扩展到 second 值,尤其是在存在重复值的情况下。

答案 1 :(得分:0)

看起来你想要pivot这个数据,但使用Linq而不是T-SQL。 (或其他一些SQL方言)

执行此操作的基本模式是使用SelectMany将每行转换为 一组键/值对,您可以OrderByDescending开启。

以下是一种有点通用的模式:

// 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);
}

答案 2 :(得分:0)

所以你有一个项目集合,可以在其中一个属性上进行排序,并且你希望集合中的两个项目具有此排序属性的最大值?

var result = myItems
    .OrderByDescending(myItem => myItem.MyProperty)
    .Take(2);

单词:按照MyProperty的降序排序整个集合,并从结果中取两个项目,这两个项目是MyProperty的最大值。

这将返回两个完整的myItem对象。通常,将更多属性从对象传输到本地内存并不是一个好主意,而不是实际计划使用。使用“选择”确保仅传输您计划使用的值:

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);