我有 2 個模型物件,DriverDetailsSourceObject用于保存 DriverDetailsAPI 回應,DriverDetailsView用于在網頁上顯示帶有聚合值的 DriverDetails 詳細資訊。
public class DriverDetailsSourceObject
{
public string Name { get; set; }
public string GroupName { get; set; }
public DateTime DateOfPurchase { get; set; }
}
public class DriverDetailsView
{
public string Name { get; set; }
public string GroupName { get; set; }
public DateTime DateOfPurchase { get; set; }
public int Count { get; set; } = 1;
public DriverDetailsView(DriverDetailsSourceObject source)
{
Name = source.Name;
GroupName = source.GroupName;
DateOfPurchase = source.DateOfPurchase;
}
}
DriverDetailsView在多個頁面上使用。在其中 2 個中Name,GroupName、DateOfPurchase和Count顯示其中Count始終為 1,而 ToTalCount 將是DriverDetailsView集合中的物件數。
| 姓名 | 數數 | 組的名字 | 日期 |
|---|---|---|---|
| 道路援助 A | 1 | A組 | 2022 年 1 月 1 日 |
| 道路援助 A | 1 | B組 | 2022 年 2 月 1 日 |
| 道路援助 A | 1 | A組 | 2/2/2022 |
| 道路援助 B | 1 | A組 | 2/2/2022 |
| 全部的 | 4 |
在其中一個頁面中,我們需要顯示按 Name 分組的所有物件并計算 Count 和 GroupNames 串列。我使用了以下 LINQ 運算式。
private IEnumerable<DriverDetailsSourceObject> DriverDetails { get; set; } = Enumerable.Empty<DriverDetailsSourceObject>();
private IEnumerable<DriverDetailsView> DriverDetailsByOption { get; set; } = Enumerable.Empty<DriverDetailsView>();
.
.
DriverDetails = DriverService.GetDriverOptions(brandName, isAgentLoggedIn);
DriverDetailsByOption = DriverDetails.GroupBy(o => o.Name)
.Select(d =>
new DriverDetailsSourceObject()
{
Name = d.First().Name,
GroupName = d.First().GroupName,
Count = d.Count()
})
.Select(v => new DriverDetailsView(v));
I am not getting the correct result using the above LINQ. Count is always 1 even after being grouped by Name. It could be because the Count has a default value 1 in DriverDetailsView, which I cannot change as it is used by other pages.
| Name | Count | Group Name |
|---|---|---|
| RoadAssistance A | 1 | Group A |
| RoadAssistance B | 1 | Group A |
| Total | 2 |
Expected result is given below:
| Name | Count | Group Name |
|---|---|---|
| RoadAssistance A | 3 | Group A, Group B |
| RoadAssistance B | 1 | Group A |
| Total | 4 |
How do I change my LINQ expression to get this result?
uj5u.com熱心網友回復:
問題 1:由于您沒有初始化CountinDriverDetailsView的建構式,因此Count默認情況下初始化為 1。
同時,您提到DriverDetailsSourceObject哪個是您的 API 回應類沒有該Count屬性。
問題 2:
在您的 LINQ 陳述句中,您回傳第一個GroupName而不是多個GroupName:
GroupName = d.First().GroupName
解決方案
對于問題 1:
我建議使用空建構式而不是DriverDetailsView(DriverDetailsSourceObject source)建構式。
public class DriverDetailsView
{
...
public DriverDetailsView() { }
...
}
對于問題 2:
要回傳 multiple GroupName,您需要選擇和 distinct GroupName,接下來使用String.Join()將GroupName陣列作為字串加入。
更改 LINQ 陳述句如下:
DriverDetailsByOption = DriverDetails.GroupBy(o => o.Name)
.Select(d => new DriverDetailsView
{
Name = d.Key,
GroupName = String.Join(",", d.Select(x => x.GroupName).Distinct()),
Count = d.Count()
});
示例程式
正如你.GroupBy()的名字,這條線
Name = d.First().Name
可以替換為:
Name = d.Key
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/445462.html
標籤:c# .net linq model-view-controller ienumerable
