Reputation: 146
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
....
Upvotes: 2
Views: 461
Reputation: 13676
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);
Upvotes: 1
Reputation: 3014
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();
Upvotes: 0