[英]How to convert the following foreach loop to linq code format?
Code: 码:
foreach (var testView in projectDataCandidate.ViewMaps
.Where(vm => !vm.IsNotTestLane)
.Select(this.GenerateTestView))
{
this.SwimLaneViews.Add(testView);
testView.ItemsOrphaned += OnItemsOrphaned;
}
How to write the above foreach loop in linq code format ? 如何以linq代码格式编写上述foreach循环? Thanks. 谢谢。
projectDataCandidate.ViewMaps
.Where(vm => !vm.IsNotTestLane)
.Select(this.GenerateTestView)
.ToList()
.ForEach(testView =>
{
this.SwimLaneViews.Add(testView);
testView.ItemsOrphaned += OnItemsOrphaned;
});
As others have already pointed out, you're already using LINQ for your query, and LINQ is for queries rather than commands. 正如其他人已经指出的那样,您已经在使用LINQ进行查询,而LINQ则用于查询而不是命令。
I think you're trying to improve the readability of your code. 我认为您正在尝试提高代码的可读性。 To do this, I suggest you extract out the query and command into different class members: 为此,建议您将查询和命令提取到不同的类成员中:
private IEnumerable<ViewMap> TestViews
{
get
{
return projectDataCandidate.ViewMaps
.Where(vm => !vm.IsNotTestLane)
.Select(this.GenerateTestView);
}
}
private void Process(ViewMap testView)
{
this.SwimLaneViews.Add(testView);
testView.ItemsOrphaned += OnItemsOrphaned;
}
Then your logic becomes the following, which is easy to read: 然后,您的逻辑将变得很容易理解:
private void ProcessTestViews()
{
foreach (var testView in TestViews)
Process(testView);
}
If you still don't like the look of the foreach
, you could do this, which I think is even easier to read: 如果您仍然不喜欢foreach
的外观,则可以执行此操作,我认为它更易于阅读:
private void ProcessTestViews()
{
TestViews.ToList().ForEach(Process);
}
ToList
删除多余的ToList
If you don't want to convert the result to a List
since it's not really needed, you could write an extension method to provide ForEach
for IEnumerable<T>
: 如果您不想将结果转换为List
因为它不是真正需要的,则可以编写扩展方法来为IEnumerable<T>
提供ForEach
:
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> elements, Action<T> action)
{
foreach (var element in elements)
action(element);
}
}
This allows you to simplify your method a bit further: 这使您可以进一步简化方法:
private void ProcessTestViews()
{
TestViews.ForEach(Process);
}
try 尝试
projectDataCandidate.ViewMaps.Where(vm => !vm.IsNotTestLane)
.Select(this.GenerateTestView).ForEach(xx=>xx.Your logic)
The only way to do this that I can see is to force execution with a ToList, then use the ForEach function. 我可以看到的唯一方法是使用ToList强制执行,然后使用ForEach函数。
var objects = projectDataCandidate.ViewMaps
.Where(vm => !vm.IsNotTestLane)
.Select(this.GenerateTestView)
.ToList();
objects.ForEach(a => SwimLaneViews.Add(a));
objects.ForEach(a => a.ItemsOrphaned += OnItemsOrphaned);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.