ProudlyTM
ProudlyTM

Reputation: 33

C#: Count occurrences of a string in a list which is in another list using LINQ?

I am trying to count occurrences of a string in dynamically added lists in a main list. This is the main list:

public static List<string>[] tables = new List<string>[30];

This is how I add items to it:

public static int takenTablesDayTotal;

public static void AddProductToTable()
{
    int tableNum = int.Parse(Console.ReadLine());

    if (tableNum < 1 || tableNum > 30) { throw new Exception(); }

    choiceName = Console.ReadLine();

    if (tables[tableNum] is null)
    {
        tables[tableNum] = new List<string>();
        takenTablesDayTotal++;
    }

    tables[tableNum].Add(choiceName);
}

And this is how I have tried to do the counting, but it doesn't seem to work right for some reason (starts at 1 and stops counting there when the required string is detected)

salesProductDayTotal = tables.Where(s => s != null && s.Contains("string")).Count();

I'm not sure how to make this work, so any help will be appreciated!

Thanks in advance!

Upvotes: 3

Views: 886

Answers (2)

Roberson Liou
Roberson Liou

Reputation: 126

You can use SelectMany to deliminate the two-nest structure. Then use Count to get what you want.

For example - count the daily apple sales number

List<string>[] tables = new List<string>[30];
tables[0] = new List<string>{
    "Apple", "Banana", "Cherry"
};
tables[1] = new List<string>{
    "Peach", "Apple", "Watermelon"
};
tables[2] = new List<string>{
    "Mango", "Grape", "Apple"
};

//the daily sales count of Apple.
var dailyAppleSalesCount = tables.Where(x => x != null)
        .SelectMany(s => s).Count(x => x == "Apple");

Upvotes: 4

Pac0
Pac0

Reputation: 23129

You can use SelectMany to flatten the List<List<string>> into one large List<string>, and then count the products.

You don't need to use Contains, IMO ("Chicken soup" is probably a different product on the menu that "Spicy Chicken Soup"), so it simplifies the condition a bit.

salesProductDayTotal = tables
    .Where(t => t != null)
    .SelectMany(products => products)
    .Count(p => p == "string")

You could also use a GroupBy clause to do this calculations on all the products at once.


Explanation of your problem:

You were using the Count on the outer list, the list of tables. So you had just "one match" for each table that contains the product at least once.

Upvotes: 3

Related Questions