c# - 合并两个集合,但仅适用于具有匹配 id 的对象

标签 c# linq c#-4.0 collections

首先,如果这是明显的重复,我深表歉意,我搜索了所有可能产生结果的短语,但很难找到答案/连贯地构建我的搜索词。

我有对象 A 的集合 1 和集合 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)));

但这感觉真的很笨拙而且不是最佳的:(

最佳答案

尝试以下操作

var result = collection1
  .Where(x => collection2.Any(c => c.Type == x.Type))
  .Union(collection2);

基本上首先过滤 collection1collection2 中具有 Type 值的项目,然后运行联合操作

关于c# - 合并两个集合,但仅适用于具有匹配 id 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21916160/

相关文章:

c# - 在 System.Drawing.Color 中使用十六进制颜色代码

c# - 使用 分配委托(delegate)时出错? : Syntax

C#-Linq : Unable to create a constant value of type Only primitive types or enumeration types are supported in this context.

c# - 位图到 int[] 使用 Marshal.Copy()

c# - Intellisense 停止为 Linq to Entities 工作

vb.net - 如何从字体文件名获取字体属性?

c# - Registry.LocalMachine 和 RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default) 之间有什么区别

c# - 在 C# 中使用 linq 更新 xml

c# - 需要时髦的 LINQ

c# - XPath 查询不起作用