问题
I cuurently have a list of objetcs Cars The variables within are:
Make
Model
Service Cost
Lets say I have the list filled up with:
Ferrari, F50, 300
Porsche, 911, 700
Toyota, Camary, 300
Porsche, 911, 400
BMW, Z4, 1200
Porsche, 911, 900
Porsche, 356A, 700
As you can see, my list contains three records where the Porsche 911 has service costs.
How would I loop through my list, find the duplicate 911's and combine them to form one single record? So that I end up with:
Ferrari, F50, 300
Porsche, 911, 2000
Toyota, Camary, 300
BMW, Z4, 1200
Porsche, 356A, 700
What I've done so far is not going to work, as my records would propbably end up in the wrong areas:
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
So in all,I have tried, but I cannot come up with a better way to store the values and combine my records.
回答1:
The easiest way is to use LINQ's Enumerable.GroupBy
and 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();
回答2:
void Main()
{
var cars = new List<Car>
{
new Car { Make = "Ferrari", Model = "F50", ServiceCost = 1000 },
new Car { Make = "Ferrari", Model = "F50", ServiceCost = 2000 },
new Car { Make = "Porsche", Model = "911", ServiceCost = 2000 }
};
var grouped = cars.GroupBy(car => car.Make + car.Model).Select(g => new { g.Key, Costs = g.Sum(e => e.ServiceCost), Element = g.First() });
foreach (var g in grouped)
{
Console.WriteLine("{0} {1}: {2}", g.Element.Make, g.Element.Model, g.Costs);
}
}
class Car
{
public string Model { get; set; }
public string Make { get; set; }
public decimal ServiceCost { get; set; }
}
来源:https://stackoverflow.com/questions/41097071/loop-through-a-list-and-combine-totals-where-an-identifier-is-the-same