Using LINQ to group a list of strings based on known substrings that they will contain

后端 未结 1 1209
不思量自难忘°
不思量自难忘° 2021-01-03 16:58

I have a known list of strings like the following:

List groupNames = new List(){\"Group1\",\"Group2\",\"Group3\"};
相关标签:
1条回答
  • 2021-01-03 17:11

    That looks like:

    var query = from groupName in groupNames
                from data in dataList
                where data.StartsWith(groupName)
                group data by groupName;
    

    Note that this isn't a join, as potentially there are overlapping group names "G" and "Gr" for example, so an item could match multiple group names. If you could extract a group name from each item (e.g. by taking everything before the first dot) then you could use "join ... into" to get a group join. Anyway...

    Then:

    foreach (var result in query)
    {
        Console.WriteLine("Key: {0}", result.Key);
        foreach (var item in result)
        {
            Console.WriteLine("  " + item);
        }
    }
    

    If you really need the anonymous type, you can do...

    var query = from groupName in groupNames
                from data in dataList
                where data.StartsWith(groupName)
                group data by groupName into g
                select new { g.Key, DataList = g.ToList() };
    
    0 讨论(0)
提交回复
热议问题