0

I have following code

var list = new List<KeyValuePair<string, int>>();

list.Add(new KeyValuePair<string, int>("Cat", 1));
list.Add(new KeyValuePair<string, int>("Cat", 2));
list.Add(new KeyValuePair<string, int>("Rabbit", 4));

Now I am trying to pass "Cat" and I should get sum of these keys in a variable.If I pass Rabbit, pass only that number

How to get this ? thinking of for-each....

5
  • 3
    I don't know what you mean by "If Keys are not equal, pass only that number" Commented Feb 21, 2018 at 12:32
  • Would a Dictionary better fit your needs? Commented Feb 21, 2018 at 12:32
  • What's your call on this? Did you try anything? Did it work? What issue did you face? Commented Feb 21, 2018 at 12:33
  • I just thought about list and written code. Which is best? list or Dictionary Commented Feb 21, 2018 at 12:33
  • 1
    Use a real class instead of KeyValauePair, for example a Pet class. Then store these pets in a List<Pet>. I guess the value is the age, so you could provide a property DateTime Birthdate. The Age property would be calculated: int Age => DateTime.Today.Year - Birthdate.Year;. Commented Feb 21, 2018 at 12:34

1 Answer 1

10

Here is a Linq appraoch with Where() and Sum()

int result = list.Where(x => x.Key == "Cat").Sum(x => x.Value);

or

int result = list.Sum(x => x.Key == "Cat" ? x.Value : 0);
Sign up to request clarification or add additional context in comments.

4 Comments

if I pass "Rabbit", it will get only that number ( ie 4) ?
@aniltc You could try it
new to LInq @Paparazzi
@aniltc: That doesn't stop you from trying it though, does it? Curiosity is important for learning things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.