[英]Finding Min & Max of a column for each identical value in another column
I have a table in an EXCEL file as follows (I can read the excel file, thats not the problem here) -我在 EXCEL 文件中有一个表,如下所示(我可以读取 excel 文件,这不是问题所在) -
+------------+-------+-------------+--------+-------+
| Date | RefNo | MasterName | Value | Type |
+------------+-------+-------------+--------+-------+
| 01-01-2020 | 45 | ABC Pty Ltd | 123.45 | Sales |
| 01-01-2020 | 2 | XYZ Ltd | 134.5 | Sales |
| 01-01-2020 | 46 | ABC Pty Ltd | 765 | Sales |
| 01-01-2020 | 47 | ABC Pty Ltd | 465.4 | Sales |
| 01-01-2020 | 3 | XYZ Ltd | 468 | Sales |
| 01-01-2020 | S_1 | ABC Pty Ltd | 678 | Sales |
| 01-01-2020 | S_2 | XYZ Ltd | 68 | Sales |
+------------+-------+-------------+--------+-------+
I use the following query to get the total amount against each 'Master' for each day (example table has only one day of sales) -我使用以下查询来获取每个“主”每天的总金额(示例表只有一天的销售) -
var query = data.GroupBy(row => new { row.Date, row.MasterName, row.Type })
.Select(grp => new MasterAccount
{
Date = grp.Key.Date,
Name = grp.Key.MasterName,
Type = grp.Key.Type,
Amount = grp.Sum(c => c.Value)
MinRef = // Get minimum ref no. (type: int)
MaxRef = // Get maximum ref no. (type: int)
});
Note: As you can see, right now my code doesn't get the RefNo column when performing the 'GroupBy' cause if I do that, then it would create a new MasterAccount against each RefNo.注意:如您所见,现在我的代码在执行“GroupBy”时没有获得 RefNo 列,因为如果我这样做,那么它将针对每个 RefNo 创建一个新的 MasterAccount。 And I dont want that.
我不想那样。
I want to get the MinRef and MaxRef against each master .我想针对每个 master 获取 MinRef 和 MaxRef 。 So in case of ' ABC Pty Ltd ' that would be 45 & 47 respectively, while ignoring the string ' S_1 '.
因此,如果是“ ABC Pty Ltd ”,则分别为45 和 47 ,而忽略字符串“ S_1 ”。 Perhaps use TryParse to make sure that it isn't a string that cannot be converted into an int.
也许使用 TryParse 来确保它不是无法转换为 int 的字符串。
But I am not sure how to implement it within this code.但我不确定如何在这段代码中实现它。
Define function which converts string to int?定义将字符串转换为int的function? (null when converstion is not possible)
(无法转换时为空)
private int? StrToInt(string s)
{
int i;
if (int.TryParse(s, out i))
return i;
else
return null;
}
and then use it in the LINQ expression:然后在 LINQ 表达式中使用它:
MinRef = grp.Min(i => StrToInt(i.RefNo).GetValueOrDefault(0),
MaxRef = grp.Max(i => StrToInt(i.RefNo).GetValueOrDefault(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.