刪除UNMATCH項目最近我遇到了我的工作問題,下面是源代碼,LINQ處理IEnumerable和從子實體
this.NameList = new ObservableCollection<Name>();
List<Others> others1 = new List<Others>();
others1.Add(new Others() { Company = "Company1", School = "School1" });
others1.Add(new Others() { Company = "Company1", School = "School1" });
others1.Add(new Others() { Company = "Company1", School = "School1" });
List<Others> others2 = new List<Others>();
others2.Add(new Others() { Company = "Company2", School = "School2" });
others2.Add(new Others() { Company = "Company2", School = "School2" });
others2.Add(new Others() { Company = "Company2", School = "School2" });
List<Others> others3 = new List<Others>();
others3.Add(new Others() { Company = "Company3", School = "School3" });
others3.Add(new Others() { Company = "Company3", School = "School3" });
others3.Add(new Others() { Company = "Company3", School = "School3" });
this.NameList.Add(new Name() { FirstName = "Jacob", LastName = "Deng", Others = others1 });
this.NameList.Add(new Name() { FirstName = "David", LastName = "Xu", Others = others2 });
this.NameList.Add(new Name() { FirstName = "Helen", LastName = "Liu", Others = others3 });
please click here to see the output of above code
然後請閱讀下面的代碼,
List<Others> others1 = new List<Others>();
others1.Add(new Others() { Company = "Company1", School = "School1" });
others1.Add(new Others() { Company = "Company1", School = "School1" });
others1.Add(new Others() { Company = "Company1", School = "School1" });
List<Others> others2 = new List<Others>();
List<Others> others3 = new List<Others>();
this.NameList.Add(new Name() { FirstName = "Jacob", LastName = "Deng", Others = others1 });
this.NameList.Add(new Name() { FirstName = "David", LastName = "Xu", Others = others2 });
this.NameList.Add(new Name() { FirstName = "Helen", LastName = "Liu", Others = others3 });
Please click here for the output of the second snippet code
從上面的兩個片段中,您可能會注意到第二個片段不包含other2和other3中的任何項目,您可以從預覽輸出中輕鬆理解。
現在問題來了,我們如何使用LINQ to IEnumerable來處理這種情況,如何使用LINQ從其他實體中刪除這些項目?但我們需要保持other2和other3不爲空(保持計數爲0)。除了LINQ之外,還有其他解決方案嗎?
我嘗試使用以下,但失敗了,
var others = ((MyVM)DataContext).NameList.Select(n => n.Others.Where(o => o.School == "School1")).ToList();
我只是做了一些測試,如果我們不使用LINQ,那麼我們可以使用下面的代碼片段,以解決我的吧。
ObservableCollection<Name> nameList = ((MyVM)DataContext).NameList;
foreach(Name n in nameList)
{
List<Others> removeList = new List<Others>();
for(int i=0;i<n.Others.Count;i++)
{
if(n.Others[i].School!="School1")
{
removeList.Add(n.Others[i]);
}
}
foreach(Others other in removeList)
{
n.Others.Remove(other);
}
}
但它看起來很冗餘,我們知道LINQ是非常有用的,我相信它可以用LINQ修復。希望有人能幫我用LINQ修復它,謝謝。
欣賞有人能幫助我。非常感謝。
試試這個列表:VAR他人=((MyVM)的DataContext).NameList.Select(N => n.Others.Select(鄰=>(o.School ==「School1」)?o:「在此處添加代碼以執行其他操作」))。ToList(); – jdweng
謝謝Jdweng,我只是想刪除那些學校不等於'學校1'LINQ的項目,並且輸出與上面提到的第二個片段代碼相同。你可以幫幫我嗎? – Jacob
這意味着當o.School!='School1',然後從其他實體中刪除該項目 – Jacob