Skip to main content
 首页 » 编程设计

c#之LINQ 选择不同类型集合中的项目

2024年01月28日26dflying

如何实现 LINQ 从一个类型 A 的对象集合中提取 Guid,以便他们可以从另一个类型 B 的对象集合中排除这些 Guid。对象 A 和对象 B 都有一个名为“ID”的 Guid 字段。 "

我有以下内容:

  1. ObservableCollection<Component> component组件有一个 字段名为 ID类型 Guid
  2. ObservableCollection<ComponentInformation> ComponentInformationCollection组件信息 有一个名为 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()); 

感谢您: Jason - 我用它作为我最终解决方案的模板(如下所列)。 Servy - 虽然我本可以使用比较器,但我认为对于这种特定情况,比较器不是必需的,因为它属于一次性使用类型。

ComponentInformationCollection 是一个 Silverlight DependencyProperty,它会在更改时触发 INotifyChangedEvent(MVVM 模式),因此上面的解决方案最适合我的情况。

请您参考如下方法:

我会这样做:

var ids = new HashSet<Guid>( 
              component.Select(x => x.ID) 
          ); 
var keepers = ComponentInformationCollection.Where(x => !ids.Contains(x.ID));