我当然有一个objetcs汽车列表其中的变量是:
使
模型
服务成本
让我们说清单填满了:
法拉利,F50,300
保时捷,911,700
丰田,Camary,300
保时捷,911,400
宝马,Z4,1200
保时捷,911,900
保时捷,356A,700
如您所见,我的列表包含保时捷911有服务费用的三条记录.
我如何遍历我的列表,找到重复的911并将它们组合成一个单独的记录?所以我最终得到:
法拉利,F50,300
保时捷,911,2000
丰田,Camary,300
宝马,Z4,1200
保时捷,356A,700
我到目前为止所做的事情是行不通的,因为我的记录可能最终会出现在错误的区域:
List<Car> CombinedCarRecords = new List<Car>(CarDetailRecords); //Original list here being used
List<Car> NormalList = new List<Car>();
List<Car> NewList = new List<Car>();//Making new lists to keep the records in
Car normalRecord = new Car();
Car combinedRecord = new Car();//new objects to keep the values in and add the others
string oldVal = "";
string newVal = "";//used to find the same cars
foreach (var item in CombinedCarRecords )
{
normalRecord = new ClaimDetailRecord();
combinedRecord = new ClaimDetailRecord();
oldVal = newVal;
newVal = item.Model;
if (oldVal == newVal)
{
combinedRecord = item;
CombinedCarRecords.Add(combinedRecord);
}
else
{
normalRecord = item;
NormalList.Add(normalRecord);
}
}//I think the way I try to find the records here is not working, as the old and new values will always be different, if maybe not for some records where they are right after each other. But there is still that initial one
decimal totalP = 0;
if (CombinedTariffsRecords.Count > 0)
{
foreach (var item in CombinedTariffsRecords)
{
}
}
else
NewList = NormalList;
//This is where I'm supposed to add up the totals, but I think my code before will render this code useless
Run Code Online (Sandbox Code Playgroud)
总而言之,我尝试过,但我无法想出更好的方法来存储值并合并我的记录.
最简单的方法是使用LINQ Enumerable.GroupBy
和Sum
:
var newCarList = NormalList
.GroupBy(c => new { c.Make, c.Model })
.Select(carGroup => new Car{
Make = carGroup.Key.Make,
Model = carGroup.Key.Model,
ServiceCost = carGroup.Sum(c => c.ServiceCost)
})
.ToList();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
93 次 |
最近记录: |