如何實現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