【发布时间】:2014-02-20 18:12:23
【问题描述】:
首先道歉,如果这是一个明显的重复,我搜索了所有可能产生结果的短语,但很难找到答案/连贯地构建我的搜索词。
我有一个集合 1 和一个对象 A 的集合 2。
// Object A Structure
Date
Type
Value
集合 1 涵盖 2 种类型的日期 1 至 2,集合 2 涵盖 1 类型的日期 3 至 4:
// Collection 1
[0] = 1st, TypeA, 3
[1] = 2nd, TypeA, 3
[2] = 1st, TypeB, 57
[3] = 2nd, TypeB, 57
// Collection 2
[0] = 3rd, TypeB, 57
[1] = 4th, TypeB, 58
我最初的要求是将这两个集合结合起来。没问题:
var result = collection1.Union(collection2);
但是,我现在想合并两个集合,但不包括集合 1 中的对象,其中集合 2 中不存在类型:
// Result Collection
[0] = 1st, TypeB, 57
[1] = 2nd, TypeB, 57
[2] = 3rd, TypeB, 57
[3] = 4th, TypeB, 58
我确信有一个简单的(希望是 linq)单行解决方案,但我就是无法让我的大脑开始思考它是什么。
到目前为止,我得到的最好的(两行)是:
// Get distinct Types from Collection 2
var typesToInclude = collection2.GroupBy(c => c.Type).Select(group => group.First().Type);
var result = collection2.Union(collection1.Where(c => typesToInclude.Contains(c.Type)));
但这感觉真的很笨重而且不是最佳的:(
【问题讨论】:
标签: c# linq c#-4.0 collections