Working with tuples in C #

I have the following code working with Tuples. Input is a list of items, output is a list of tuples, and we need to calculate the number of items for each date basically.

List<Tuple<DateTime, int>> list = new List<Tuple<DateTime, int>>();
foreach (ItemClass item in items)
{
    foreach(Tuple<DateTime, int> tuple in list)
    {
         if (tuple.Item1 == item.date)
         {
              tuple.Item2++;
              continue;
          }
    }
    list.Add(Tuple.Create<DateTime, int>(item.date, 1)); 
}

      

This code does not currently compile because it Item2

is read-only, the question is how to get it to work?

This used to work with Dictionary

, but I had to remove it because it was not acceptable for external code to work with Dictionary

.

+3


source to share


3 answers


Tuples are not intended for use in scenarios where mutability is needed. You can create your own class that combines DateTime

with a mutable integer counter, but you can also do this with LINQ by converting it to a list of tuples at the very end:

var list = items
    .GroupBy(item => item.date)
    .Select(g => Tuple.Create(g.Key, g.Count()))
    .ToList();

      



The above code creates a group for each date and then creates tuples only when the final element counts in each group are known.

+7


source


Try using Linq GroupBy()

to group by date, then use Select()

and create a tuple for each group, and finally convert to a list using ToList()

. Something like



var result = items.GroupBy(x => x.Date)
                  .Select(x => Tuple.Create(x.Key, x.Count()))
                  .ToList();

      

+4


source


I guess because it only reads that it already has a property, I think I used a tuple before, so yes, it might be.

You may not be able to edit it, because you can edit the iterators in the Foreach () loop, perhaps experiment with a different type of loop.

OR

Set item2 to an object outside of the current loop and use it instead of an iterator.

-1


source







All Articles