Home > database >  C# Searching String from list and add its Integer if there is more than one result
C# Searching String from list and add its Integer if there is more than one result

Time:07-27

this is my list

var list1 = new List<KeyValuePair<string, int>>();
            list1.Add(new KeyValuePair<string, int>("Narzo", 8));
            list1.Add(new KeyValuePair<string, int>("Stinger", 5));
            list1.Add(new KeyValuePair<string, int>("Stinger", 2));

I want to search a string and display the string together with the integer. If the string has duplicate value then it will add the integer of the duplicate/s

Sample

INPUT:

Search "Stinger"

OUTPUT:

Stinger 5

Stinger 2

Stinger 7

CodePudding user response:

If you just want to sum the values of the duplicate-keys and output them, use LINQ:

var duplicates = list1.GroupBy(kv => kv.Key)
                      .Where(g => g.Count() > 1)
                      .Select(g => $"{g.Key} {g.Sum(kv => kv.Value)}");

foreach(var duplicate in duplicates)
    Console.WriteLine(duplicate); // Stinger 7

CodePudding user response:

var searchFor = "Stinger";
Console.WriteLine($"{searchFor} {list1.Where(w => w.Key == searchFor).Sum(x=>x.Value)}");

CodePudding user response:

Seems like a simple loop plus a variable to keep track of the count and sum would work:

Pseudo-code

string search = "Stinger";
int count = 0;
int sum = 0;
foreach(var kvp in list1)
{
    if the item matches the search
    {
        increment the count
        add the value to the sum
        print the item
    }
    if more than one item found
    {
        print the search string and sum of values
    }
}
  •  Tags:  
  • c#
  • Related