[英]IEnumerable Best Practice of removing int item
I have a IEmunerable list with N items for example: 23, 1, 38..... 我有一个包含N个项目的IEmunerable列表,例如:23、1、38 .....
The needed logic is, when looping thru the list: 遍历列表时,所需的逻辑是:
1: find if 1exist 1:查找是否存在1
2: if 1 exist, find 2 2:如果存在1,则找到2
3: if 2 exist, find 3 3:如果存在2,则找到3
4: If 3 exist, remove 3 from the current list. 4:如果存在3,则从当前列表中删除3。
My current approach is: 我当前的方法是:
foreach(var x in someIntList)
{
if(x==1)
{
if(someIntList.Any(y => y==2))
{
if(someIntList.Any(z => z==3))
{
//This is the shortest code i can think of, but apparently its wrong. Error saying there is no Except method for IEmunerable<Int> ?
someIntList = someIntList.Except(3);
}
}
}
}
You need to pass IEnumerable<int>
to except, like this 您需要将
IEnumerable<int>
传递给except,像这样
someIntList = someIntList.Except(new[] {3});
read more about Except on MSDN 在MSDN上阅读有关Except的更多信息
To remove better use this, I can't imagine shorter version: 为了更好地使用它,我无法想象更短的版本:
if(someIntList.Contains(1)&&someIntList.Contains(2)&&someIntList.Contains(3))
{
someIntList.Remove(3); // **if it's a list**
someIntList = someIntList.Except(3); //**if it's a IEnumerable**
}
Snippet 片段
var x = new List<int> {5, 4, 3, 2, 1};
if(x.Contains(1) && x.Contains(2) && x.Contains(3)) x.Remove(3);
Just in case... 以防万一...
IEnumerable<int> y = new List<int> {5,4,3,2,1};
So if you are getting an IEnumerable from your method. 因此,如果您从方法中获得IEnumerable。
var x = y.ToList()
If you need to remove all, x.RemoveAll(z=>z == 3); 如果需要删除所有内容,请x.RemoveAll(z => z == 3);
It's not clear why you're looping to start with, or using Any
instead of Contains
: 目前尚不清楚为什么要循环开始,还是使用
Any
而不是Contains
:
if (someIntList.Contains(1) && someIntList.Contains(2) && someIntList.Contains(3))
{
someIntList = someIntList.Where(x => x != 3); // Possibly with ToList()?
}
You probably don't want to use Except
as that's a set-based operation - if your original list contains duplicates, they will be removed if you use Except
. 您可能不希望使用
Except
因为这是基于集合的操作-如果您的原始列表包含重复项,那么如果您使用Except
,则会将其删除。
Note that this will remove all occurrences of 3 - is that what you want, or do you just want to remove the first occurrence of 3? 请注意,这将删除所有出现的3-是您想要的,还是只想删除第一个出现的3?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.