2017-03-02 29 views
-3

使用lambda表達式根據條件刪除內部列表元素。我已經通過foreach達成了。需要使用lambda表達式或LINQ使用lambda表達式根據條件刪除內部列表元素

實現

請幫

if (!FwContext.User.UserRoles.Exists(s => s.RoleCd == "Admin")) 
{ 
    foreach (var item in items.ToList()) 
    { 
     foreach (var attribute in item.ItemAttributeValues.ToList()) 
     { 
      if (attribute.AttributeNm == "EST" && attribute.StatusNm == "SAP") 
      { 
       item.ItemAttributeValues.Remove(attribute); 
      } 
     } 
    } 
} 
+0

在遍歷它不能修改的集合。 – dcg

+0

這是家庭嗎?如果您需要使用lambda表達式或linq來完成,爲什麼要使用foreach循環? –

+1

如果我們使用.ToList(),我們可以修改一個集合,並且上面的代碼工作正常,沒有任何錯誤。 – NishanthMV

回答

0

喜歡這個?

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace RemoveItemFromListWithLinq_42565975 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DoIt(); 
     } 

     private static void DoIt() 
     { 
      List<string> thelist = new List<string>() { "file1", "file2", "file3" }; 
      thelist = thelist.Where(p => p != "file2").ToList(); 
      Console.WriteLine(string.Join(",", thelist)); 
      Console.ReadLine(); 
     } 
    } 
} 

喜歡你開後

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace RemoveItemFromListWithLinq_42565975 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      DoIt(); 
     } 

     private static void DoIt() 
     { 
      List<string> thelist = new List<string>() { "file1", "file2", "file3" }; 
      thelist = thelist.Where(p => p.Length == 5 && p != "file2").ToList(); 
      Console.WriteLine(string.Join(",", thelist)); 
      Console.ReadLine(); 
     } 
    } 
} 
+0

這不會工作。我必須從內部列表中刪除元素。我的問題是與另一個列表中的列表。 – NishanthMV

+0

項目是一個列表,ItemattributeValues是項目 – NishanthMV

0

目前我發現使用屬性如下。它工作正常。

items.ToList().ForEach(item => 
        { 
        var attr = item.ItemAttributeValues.ToList().Where(x => x.AttributeNm == "EST" && x.StatusNm == "SAP").FirstOrDefault(); 
        item.ItemAttributeValues.Remove(attr); 
        } 
       ); 

請告訴我們是否可以以更好的方式做到這一點。

+0

中的另一個列表,如果您想添加信息到您的文章,請使用您的文章下方的[編輯按鈕](http://stackoverflow.com/posts/42565975/edit)。請不要發佈其他信息作爲答案。 –

0
items.ToList().ForEach(item => item.ItemAttributeValues.Remove(item.ItemAttributeValues.ToList().ToList().Where(x => x.AttributeNm == "EST_DIE_SZ_AREA" && x.StatusNm == "SAP Adopted").FirstOrDefault())); 

一聲查詢小改

+0

如果您想添加信息到您的文章,請使用您的文章下方的[編輯按鈕](http://stackoverflow.com/posts/42565975/edit)。請不要發佈其他信息作爲答案。 –

相關問題