Home > Blockchain >  How can I create a list of each item in another list, and the count of how many times that item appe
How can I create a list of each item in another list, and the count of how many times that item appe

Time:12-23

So I have a list of items -> A, B, C, D.

C and D are included more than once, and A and B, more than twice. This list can go on and on, so we do not know how many times an item will be included.

list

I need to create a new list that will have the item in one column and the number of instances of that item in another column, but I do not know how to do this. I may need to use a tuple or a class, but I am not fully sure how to implement either...

CodePudding user response:

What you actually need is to Group the items of your list and perform a group operation, which is Count in your case to calculate how many times does it exist.

This is how you may initialize your list:

List<string> myList = new List<string>() { "A", "B", "C", "D", "A", "B", "C", "D", "A", "B" };

and then you will group it using GroupBy function and apply the Count aggregate function on each group.

myList
.GroupBy(item => item)
.Select(g => new {Key = g.Key, Count = g.Count()})
.ToList();

This will result in the table you need.

CodePudding user response:

You can try like this:

var myList = new List<String>() { "A","B", "C", "D","A","B", "C", "D", "A","B"};
var grp = myList.GroupBy( x => x );
foreach( var g in grp )
{
  Console.WriteLine( "{0} {1}", g.Key, g.Count() );
}

DOTNET FIDDLE

CodePudding user response:

char[] items = new[] { 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B' };
Dictionary<char, int> counts = new();
foreach(char c in items)
{
    if (counts.TryGetValue(c, out int n))
    {
        counts[c] = n   1;
    }
    else
    {
        counts.Add(c, 1);
    }
}

While not a one liner, a simple and fast option.

CodePudding user response:

I may need to use a tuple or a class, but I am not fully sure how to implement either...

Since you mentioned you may want to use a class, here is an example:

public class TextCount
{
    public string Text { get; set; }
    public int Count { get; set; }
}

public class Program
{
    public static void Main()
    {
        // Initialize the list of strings
        List<string> data = new List<string> { "A", "B", "C", "D", "A", "B", "C", "D", "A", "B" };

        // Use LINQ to group the strings by their value and count the number of occurrences of each string
        List<TextCount> result = data
            .GroupBy(s => s)
            .Select(g => new TextCount { Text = g.Key, Count = g.Count() })
            .ToList();

        // Print the results
        foreach (TextCount sc in result)
        {
            Console.WriteLine("{0}: {1}", sc.Text, sc.Count);
        }
    }
}

Demo: https://dotnetfiddle.net/2FRBbK

  •  Tags:  
  • c#
  • Related