代码之家  ›  专栏  ›  技术社区  ›  Bullines

获取第一次出现的值

  •  0
  • Bullines  · 技术社区  · 6 年前

    我尝试首先出现按特定属性分组的值。

    我有一张单子, monthlyResults ,其中包含对象列表。对象定义为:

    class MyObj {
        public string PropA;
        public string PropB;
        public string PropC;
    }
    

    样本数据 初步结果 可能是这样的:

    monthlyResults[0]
        monthlyResults[0][0] // { PropA = "2018-09", PropB = "foo", PropC = "apple" }
        monthlyResults[0][1] // { PropA = "2018-09", PropB = "bar", PropC = "banana" }
        monthlyResults[0][2] // { PropA = "2018-09", PropB = "baz", PropC = "apple" }
    monthlyResults[1]
        monthlyResults[1][0] // { PropA = "2018-10", PropB = "quux", PropC = "banana" }
        monthlyResults[1][1] // { PropA = "2018-10", PropB = "qux", PropC = "cherry" }
        monthlyResults[1][2] // { PropA = "2018-10", PropB = "bar", PropC = "cherry" }
        monthlyResults[1][3] // { PropA = "2018-10", PropB = "foo", PropC = "apple" }
    

    好消息是 初步结果 已按所需属性分组- PropA . 但是,我希望能够获得 PropC 属性,使我的结果如下所示:

    firstOccurrences[0] // this would be for "2018-09"
        ["apple", "banana"]
    firstOccurrences[1] // this would be for "2018-10"
        ["cherry"]
    

    因此,在本例中,Propa的值为“apple”的对象首先出现在“2018-09”组中。“香蕉”也一样。其中“cherry”首次出现在“2018-10”组。等等…

    我一直在尝试:

    monthlyResults.Select(g => g.GroupBy(r => r.PropA).Select(r => r.OrderBy(i => i.PropC).First()));
    

    但当然,这只是在每个 普罗帕 分组。我应该如何搜索整个 初步结果 集合到第一个 丙纶 值及其所在的组 普罗帕 ?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Hogan    6 年前
    System.Collections.Generic.HashSet<string> allFound = new HashSet<string>();
    
    var results = monthlyResults
      // flatten the two d array
      .SelectMany(x => x)
      // select only items we have not seen before.
      .Where(x => { 
         if (allFound.Contains(x.PropC))
           return false; 
         else { 
           allFound.Add(x.PropC); 
           return true; 
         }
       });
    
        2
  •  0
  •   Itay Podhajcer    6 年前

    你可以这样做:

    monthlyResults
        .SelectMany(monthlyResult => monthlyResult)
        .OrderBy(result => result.PropA)
        .GroupBy(result => result.PropC)
        .Select(propCGroup => propCGroup.First())
        .GroupBy(firstOccurence => firstOccurence.PropA);
    

    不在前面 可视演播室 ,所以可能会有一些错别字,但我认为它应该给你所需要的。

    希望它有帮助!