c# - tlv解析 - 组数据具有唯一的键和值




tlv编码 (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