我正在尝试第一次出现按特定属性分组的值。
我有一个列表,monthlyResults,它包含对象列表。这些对象被定义为:
class MyObj {
public string PropA;
public string PropB;
public string PropC;
}monthlyResults中的示例数据可能如下所示:
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" }好的是monthlyResults已经按照我想要的属性- 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”组中。“香蕉”也是。作为“樱桃”最早出现在"2018-10“组。等等..。
我一直在尝试:
monthlyResults.Select(g => g.GroupBy(r => r.PropA).Select(r => r.OrderBy(i => i.PropC).First()));但当然,这只是每个PropA分组中的第一次出现。如何搜索整个monthlyResults集合以首先找到PropC值的第一次出现以及PropA找到它们的组
发布于 2019-01-04 18:51:57
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;
}
});发布于 2019-01-04 18:59:37
你也许可以用这样的方法:
monthlyResults
.SelectMany(monthlyResult => monthlyResult)
.OrderBy(result => result.PropA)
.GroupBy(result => result.PropC)
.Select(propCGroup => propCGroup.First())
.GroupBy(firstOccurence => firstOccurence.PropA);不是在Visual 前面,所以可能会有一些排版,但我认为它应该能满足您的需要。
希望能帮上忙!
https://stackoverflow.com/questions/54044152
复制相似问题