Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        去年关闭。
                                                                                            
                
        
我当前的代码是这样的:

    var results = new List<Results>();

    var items = new List<string>
    {
        "B,0",
        "A,1",
        "B,2",
        "A,3",
        "A,4",
        "B,5",
        "A,6",
        "A,7",
        "B,8"
    };

    int size = 2;
    int temp;
    var tempResults = new List<int>();

    var keys = items.Select(t => t.Split(',')[0]).Distinct().ToList();
    //var values = items.Select(t => t.Split(',')[1]).ToList();

    //var result = items.SelectMany(k => values, (k, v) => new {k, v});

    foreach (var key in keys)
    {
        temp = 0;
        tempResults = new List<int>();
        foreach (var item in items)
        {
            if (item.Split(',')[0] == key)
            {
                tempResults.Add(Int32.Parse(item.Split(',')[1]));
                temp++;
            }

            if (temp == size)
            {
                results.Add(new Results
                {
                    Key = key,
                    Values = new List<int>(tempResults)
                });
                temp = 0;
                tempResults.Clear();
            }
        }
    }

    foreach (Results r in results)
    {
        Console.WriteLine("Key: " + r.Key);
        Console.WriteLine("Values: ");
        foreach (int i in r.Values)
        {
            Console.WriteLine(i);
        }
    }


一切正常,但是我使用两个循环来获取所需的结果。我想用LINQ表达式替换它们并一直在尝试,但似乎无法弄清楚。任何帮助表示赞赏。

最佳答案

您可以使用LINQ方法的组合:.GroupBy.SelectSelectMany和某些数据结构,例如Tuple<T1, T2>

前提是我们有课:

class Results
{
    public string Key { get; set; }
    public List<int> Values { get; set; }
}


解决方案可能是:

        int k = 0;
        var result =
            items.Select(x =>                          // parse initial string
                 {
                     var strValue = x.Split(',');
                     return Tuple.Create(strValue[0], Convert.ToInt32(strValue[1]));
                 })
                 .GroupBy(x => x.Item1, y => y.Item2)  // group by key
                 .Select(x => Tuple.Create(x.Key, x))  // flatten to IEnumerable
                 .SelectMany(x =>                      // select fixed size data chunks
                     x.Item2.GroupBy(y => k++ / size, z => z)
                            .Select(z => Tuple.Create(x.Item1, z)))
                 .Select(x =>                          // cast to resulting model type
                     new Results()
                     {
                         Key = x.Item1,
                         Values = x.Item2.ToList()
                     })
                 .ToList();                            // Return enumeration as list

关于c# - 用linq代码替换循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48369533/

10-12 22:13