C#:使用LINQ计算一个列表中另一个列表中字符串的出现次数吗?

我正在尝试计算主列表中动态添加的列表中字符串的出现次数。这是主要列表:

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

这是我向其中添加项目的方式:

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);
}

这就是我尝试进行计数的方式,但是由于某些原因,它似乎无法正常工作(从1开始并在检测到所需的字符串时停止在此处计数)

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

我不确定如何进行这项工作,因此将不胜感激!

提前致谢!

评论
  • inisi
    inisi 回复

    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.

    您的问题的解释:

    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.

  • trerum
    trerum 回复

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

    例如-计算每日苹果销量

    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");