我在想,是否有一种扩展方法允许我迭代一个列表并让我对列表中的每个项目执行相同的操作。例如:
.RemoveAll(x => x.property == somevalue)
这会移除所有满足条件的元素。但是,如果我有这个怎么办:
foreach(object item in lstObjects)
{
object MyObject = new object();
MyObject.propertyone = item.property
MyObject.propertytwo = somevalue;
anotherlist.Add(MyObject);
}
当然,真正的代码比这复杂一点。我的目标是,而不是 foreach使用扩展方法,我找到了List<T>.ForEach()但我无法让它工作,而且这个方法不存在于 var 列表中。我也找到了.Select<> , .Where<>但这会返回值,而在我的方法中不需要返回任何值。
请您参考如下方法:
var convertedItems = lstObjects.Select(item =>
{
object MyObject = new object();
MyObject.propertyone = item.property
MyObject.propertytwo = somevalue;
return MyObject;
});
anotherList.AddRange(convertedItems);
或
anotherList = convertedItems.ToList();
如果你想让它更短:
var convertedItems = lstObjects.Select(item =>
new object {propertyone = item.property, propertytwo = somevalue});
