如何实现LINQ从一个类型为A的对象集合中提取Guid,以便它们可以从另一个类型为B的对象集合中排除这些Guid。对象A和对象B两者都具有被称为“ID GUID字段“LINQ来选择不同类型的集合中的项目
我有以下:
ObservableCollection<Component> component
元器件具有 字段称为Guid
类型的ID
ObservableCollection<ComponentInformation> ComponentInformationCollection
ComponentInformation 有一个名为类型的ID
领域Guid
我的实现:
component =>
{
if (component != null)
{
var cancelledComponents = new List<ComponentInformation>();
foreach (Component comp in component)
{
cancelledComponents.Add(new ComponentInformation() { ID = comp.ID });
}
this.ComponentInformationCollection.Remove(cancelledComponents);
}
});
我相信有一个更优雅的解决方案,我在一直在努力解决,但我一直运行到是问题创建一个'新的ComponentInformation',这样的类型不会给我一个错误。
======最终解决=======
var cancelledComponentIDs = new HashSet<Guid>(component.Select(x => x.ID));
this.ComponentInformationCollection.Remove(
this.ComponentInformationCollection.Where(x => cancelledComponentIDs.Contains(x.ID)).ToList());
谢谢: 杰森 - 我用这个作为一个模板,我的最终解决方案(见下表)。 Servy - 虽然我可以使用比较器,但我认为对于这种特殊情况,比较器并不是必需的,因为它是一次性使用的情况。
ComponentInformationCollection是Silverlight DependencyProperty,它会在更改时触发INotifyChangedEvent(MVVM模式),所以上述解决方案对我的情况最有效。
这是很多工作,只是没有定义'IEqualityComparer'的'组件'。你做了两个额外的投影,一个额外的地方,你需要把所有东西都放到HashSet中(意味着没有流式传输)。 – Servy 2012-04-06 01:42:22
我认为你也有收集倒退,如果我正在阅读正确的问题,他想从ComponentInformationCollection丢弃... – 2012-04-06 01:49:31
@Servy:我认为你错过了这一点。 – jason 2012-04-06 02:02:35