c# - multiple - 組數據具有唯一的鍵和值




linq groupby (2)

我有以下一組數字:

1  137
1  143
11 37
11 46
11 132
46 65
46 139
69 90

現在,我需要以第一個值的方式對數據進行分組,以使組值不存在組密鑰。 所以,例如,如果我只是簡單地分組數據,我會得到這樣的結果:

1  137
   143
11 37
   46
   132
46 65
   139
69 90

這裡是第三組中的組密鑰和第二組中的組值。 在這種情況下,我需要將第三組的組值合併到第二組中,並刪除第三組。 分組的最終結果應該如下所示:

1  137
   143
11 37
   46
   132
   65
   139
69 90

我對C#比較陌生,所以我想知道是否有一種奇妙的方式來使用LINQ。


這可以為你工作

public static List<Numbers> setNumbers()
{
    List<Numbers> num = new List<Numbers>();

    num.Add(new Numbers() { Column1 = 1, Column2 = 137 });
    num.Add(new Numbers() { Column1 = 1, Column2 = 143 });
    num.Add(new Numbers() { Column1 = 11, Column2 = 37 });
    num.Add(new Numbers() { Column1 = 11, Column2 = 46 });
    num.Add(new Numbers() { Column1 = 11, Column2 = 132 });
    num.Add(new Numbers() { Column1 = 46, Column2 = 65 });
    num.Add(new Numbers() { Column1 = 46, Column2 = 139 });
    num.Add(new Numbers() { Column1 = 69, Column2 = 90 });


    return num;
}


public static void group()
{
    List<Numbers> numbers = setNumbers();

    var grouppedNumbers = numbers
        .GroupBy(x => x.Column1).ToList();

    grouppedNumbers.AddRange(grouppedNumbers.FirstOrDefault(x => x.First().Column1.Equals(46)).Select(s => new Numbers() { Column1 = 11, Column2 = s.Column2 }).GroupBy(g => g.Column1).ToList());
    grouppedNumbers.Remove(grouppedNumbers.FirstOrDefault(x => x.First().Column1.Equals(46)));



    foreach (var groups in grouppedNumbers)
    {
        Console.WriteLine(groups.First().Column1);
       foreach(var i in groups)
       {
           Console.WriteLine(i.Column1+" "+ i.Column2);
       }
    }




}

試試這個LINQ解決方案:

var numbers = new List<Number>
{
    new Number {X = 1, Y = 137},
    new Number {X = 1, Y = 143},
    new Number {X = 11, Y = 37},
    new Number {X = 11, Y = 46},
    new Number {X = 11, Y = 132},
    new Number {X = 46, Y = 65},
    new Number {X = 46, Y = 139},
    new Number {X = 69, Y = 90}
};
var result = numbers.GroupBy(c => c.X);
var result2 = numbers.FirstOrDefault(c => result.Select(d => d.Key).Contains(c.Y));

var finalResult = numbers.Where(x => x.X == result2?.Y)
                         .Select(x =>  { x.X = result2.X;x.Y = x.Y; return x; } )
                         .Union(numbers.Where(c => c.X != result2?.Y)).GroupBy(c => c.X ,
                         (key, element) => new
                         {
                             Key = key,
                            Element = element.Select(c => c.Y).ToList()
                         });

結果:





group-by