CMZneu
CMZneu

Reputation: 3

Using Lambdas to access a list in a list?

I'm a beginner trying to learn to use lambdas, I have the class Character who inside has a "List<Item> inventory" which can hold "class Sword: Item" and "class Shield: Item"

I want to get a List<float> that displays the damage of each of my Characters. The damage being the sum of damages of items in their inventory(swords and shields).

So far i know i can do this to an individual character in my character list and get the sum of damage from his items.

float damage = characters[0].inventory.Select(item => item.damage).Sum(dmg => dmg);

But when i try to do all my characters at the same time this does not work.

List<float> charactersTotalDamagesFromEachCharacter = characters
            .Select(character => character.inventory)
            .Select(item => item)
            .Select(item => item.damage)
            .Sum(dmg => dmg);

I want to get a List<float> that represent the characters total damages(sum of damage of their items).

Upvotes: 0

Views: 77

Answers (2)

RePierre
RePierre

Reputation: 9566

If you want to know total damage per each character you need to just sum the damage for each characters inventory (btw, you can sum directly without selecting the property to be summed and calling Sum() afterwards):

var totalDamagePerCharacter = characters.Select(c => new
{
    Character = c,
    TotalDamage = c.Inventory.Sum(item => item.Damage)
})
.ToList();

However, if you don't need to know the specific character that incurs the damage and you're only interested in having a list of total damages, just project the character to its total damage from the query above:

var listOfTotalDamages = characters.Select(
    c => c.Inventory.Sum(item => item.Damage)).ToList();

Upvotes: 2

Rahul Singh
Rahul Singh

Reputation: 21795

I guess you are looking for individual damage, this should give you the correct result:-

List<float> charactersTotalDamagesFromEachCharacter = characters
                                           .Select(x => x.inventory.Sum(z => z.damage))
                                           .ToList();

Upvotes: 0

Related Questions