2

I want to Count the items in an associated array. I have written small piece of code but now I am thinking it will not work. What strategy should I use?

I have created a class

public class itemsList
{
     public string itemName;
     public int itemCount;
}

Calculation code is as follows (consider items in the following code an array)

foreach (var item in items)
{
     //this is pseudo, I want help in this
     if (itemsList.Contain("itemName", item)
          itemsList[item].itemCount++;
     else
          itemsList.Add(item, 1);
}

Please keep in mind this array has later to be changed to json in the following format.

"apples": 10,
"oranges": 4
....
4
  • Check if itemsList[item] comes back with nothing. Then the key doesn't exist Commented May 6, 2018 at 7:29
  • @Fabjan I think this is best answer Commented May 6, 2018 at 7:32
  • @Fabjan let me try this, never used it before, I hope it will help Commented May 6, 2018 at 7:34
  • 1
    @Fabjan thanks alot for the help. Everthing is working like I wanted now :) Commented May 6, 2018 at 8:28

2 Answers 2

1

So as already mentioned, Dictionary<TKey, TValue> here is a better choice :

private readonly Dictionary<string, int> ItemsDict = new Dictionary<string, int>();

Then all you need to do is:

string someItemName = "itemName";

if(!ItemsDict.ContainsKey(someItemName))
{
    ItemsDict.Add(someItemName, 1);
}
else 
{
    ItemsDict[someItemName]++;
}

Depending on what you need you might also want to use some class as a value:

public class itemsList
{
     public string itemName;
     public int itemCount;
}

...

private readonly Dictionary<string, itemsList> ItemsDict = new Dictionary<string, itemsList>();
// here we add an object
ItemsDict.Add(someItemName, myItem);
Sign up to request clarification or add additional context in comments.

Comments

0

You could use LINQ GroupBy and create an anonymous class with properties itemName and itemCount. Each anonymous object stored inside the list result holds the item name and the count of the item.

var result = items.GroupBy(item => item)
                  .Select(group => new
                   {
                       itemName = group.Key,
                       itemCount = group.Count()
                   }).ToList();

Comments

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.