2017-03-04 49 views
0

我有一個對象列表List<Points>,每個對象(點)都有一些屬性,如x,y和z。 (Points.x,Points.y,Points.z是雙打) 我想刪除有一些條件的對象。例如,應刪除具有x < = 5,6 < = y < 10,z < 20的對象。我怎樣才能做到這一點?有條件地從列表中刪除項目

感謝

+1

搜索上的另一個使用RemoveAll方法對於'LINQ To Obj ects',如果你的代碼不能按預期工作,請回來。 –

+3

'points.RemoveAll(point => point.X <= 5 && point.Y <= 6 ...)' – sed

回答

0

您可以使用RemoveAll方法是這樣的:

list.RemoveAll(p => p.x <= 5 && p.y >= 6 && p.y < 10 && p.z < 20); 
+1

RemoveAll列出了一個與Linq無關的方法 –

+0

您是對的。 Ty –

0

您可以使用LINQ

var pointList = new List<Point>(); 

    pointList = pointList.Where(p => 
       !((p.X <= 5) && (p.Y > 6 && p.Y < 10) && (p.Z < 20))) 
       .ToList(); 

或列表對象

pointList.RemoveAll(p => (p.X <= 5) && (p.Y > 6 && p.Y < 10) && (p.Z < 20)); 
+0

謝謝。 'List Points = new List ();'。實際上,我已經用這種方式定義了我的列表(ActivePoints是Point定義的類),每個Points都有x,y和z。我能知道'p =>'的含義是什麼嗎?我應該如何編寫我的代碼? 'OpenPoints.RemoveAll(p => px <= 5 && p.y > = 6 && py <10 && pz <20);' –

+0

p =>是Lambda表達式https://msdn.microsoft.com/zh-cn/library/bb397687.aspx ?f = 255&MSPPError = -2147217396 –

+0

如果OpenPoints包含所有點對象,則RemoveAll將刪除所有匹配由指定謂詞定義的條件的對象.https://msdn.microsoft.com/en-us/library/wdka673a(v = vs.110).aspx @KatatoniaSh –