I have a table in an EXCEL file as follows (I can read the excel file, thats not the problem here) -
+------------+-------+-------------+--------+-------+
| 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. And I dont want that.
I want to get the MinRef and MaxRef against each master . So in case of ' ABC Pty Ltd ' that would be 45 & 47 respectively, while ignoring the string ' S_1 '. Perhaps use TryParse to make sure that it isn't a string that cannot be converted into an int.
But I am not sure how to implement it within this code.
Define function which converts string to int? (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:
MinRef = grp.Min(i => StrToInt(i.RefNo).GetValueOrDefault(0),
MaxRef = grp.Max(i => StrToInt(i.RefNo).GetValueOrDefault(0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.