使用LINQ对对象集合进行排序? [英] Sorting an object collection using LINQ?

查看:90
本文介绍了使用LINQ对对象集合进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述






















您好,

我是LINQ的新手,但我有一个存储在对象中的值集合,以确定销售人员带来多少钱(称为"salesTransactions")。数据如下所示:
员工ID |员工姓名|销售交易金额
------------------------------------------- --------
1 |约翰| 18.47
2 |贝丝| 27.67
1 |约翰| 12.04
1 |约翰| 10.50
3 |艾伦| 34.87
2 |贝丝| 19.12
如何使用LINQ获取对象并显示按总收入排序的总收入,如下所示:
Beth:$ 46.79
John:$ 41.01
Allen:$ 34.87

这是否可以使用LINQ?或者是否有人知道可以告诉我如何操作的教程?

谢谢。


Hello,

I'm new to LINQ but I have a collection of values stored in an object to determine how much money a sales person is bringing in(called "salesTransactions"). The data looks like the following:
Employee ID | Employee Name | Sales Transaction Amount
---------------------------------------------------
1 | John | 18.47
2 | Beth | 27.67
1 | John | 12.04
1 | John | 10.50
3 | Allen | 34.87
2 | Beth | 19.12

How can I use LINQ to take the object and display the total earnings sorted by the total amount earned, like the following:
Beth: $46.79
John: $41.01
Allen: $34.87

Is this possible with using LINQ?  Or does someone know of a tutorial that can show me how to do this?

Thanks.

推荐答案

这对LINQ来说当然是可行的。以下是您需要的查询:

从salesTransactions中的s发送新的{s.EmployeeID,s .EmployeeName}到新的组中了一个g
let totalSales = g .Sum(s => s.Amount)
orderby totalSales descending
select g.Key.EmployeeName +":" + totalSales.ToString(" C")


首先我们按EmployeeID对销售进行分组。我们还带有EmployeeName,因为我们稍后需要显示它。接下来,我们评估每个组的总销售额。我们使用"let"因为它节省了我们不得不评估它两次(我们需要这些数据用于排序和在最终投影中显示)。然后我们按这个聚合顺序,然后选择每个组的EmployeeName(来自Key)和我们之前计算的totalSales聚合。

This is certainly possible with LINQ. Here's the query that you need:


  from s in salesTransactions
  group s by new { s.EmployeeID, s.EmployeeName } into g
  let totalSales = g.Sum (s => s.Amount)
  orderby totalSales descending
  select g.Key.EmployeeName + ": " + totalSales.ToString ("C")


First we group the sales by the EmployeeID. We also bring along the EmployeeName because we'll need to display it later on. Next, we evaluate the total sales for each group. We use a "let" clause because it saves us having to evaluate it twice (we need this data both for ordering and to display in the final projection). Then we order by this aggregate, and then select each group's EmployeeName (from the Key) and the totalSales aggregate we previously calculated.

Joe


这篇关于使用LINQ对对象集合进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆