解释这种LINQ code? [英] Explain this LINQ code?

查看:102
本文介绍了解释这种LINQ code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个问题,其中,响应的一个包含以下LINQ code:

  VAR选择= lstAvailableColors.Cast<列表项>()式(I => i.Selected).ToList();
selected.ForEach(X => {lstSelectedColors.Items.Add(X);});
selected.ForEach(X => {lstAvailableColors.Items.Remove(X);});
 

有人可以解释上面的LINQ共新手?

解决方案

LINQ的运营商采用什么叫做的流畅的界面,这样你就可以读第一行作为一系列函数调用。假设 lstAvailableColors 的IEnumerable< T> ,这个想法是,每个可用的颜色流经LINQ运营商

让我们来分析一下:

  VAR选择= lstAvailableColors
    //每一个项目被转换为列表项类型
    .Cast<列表项>()
    //未通过测试(选==真)物品掉到
    。凡(I => i.Selected)
    //转流成名单,其中,列表项>目的
    .ToList();
 

编辑:JaredPar指出,上述的最后一行(了ToList())是非常重要的。如果你不这样做,那么每两个 selected.ForEach 通话将重新运行查询。这就是所谓的延迟执行并是一个重要的LINQ的一部分。

您可以重写这样的这第一行:

  VAR选择=新的名单,其中,列表项>();

的foreach(在lstAvailableColors VAR项)
{
    VAR的listItem =(列表项)项目;

    如果(!listItem.Selected)
         继续;

    selected.Add(的listItem);
}
 

最后两行只是另一种方式来写一个foreach循环,并可能被改写为:

 的foreach(VAR的X选择)
{
    lstSelectedColors.Items.Add(X);
}

的foreach(VAR的X选择)
{
    lstAvailableColors.Items.Remove(X);
}
 

学习LINQ是学习的数据流和的拉姆达EX pressions 的。

I asked a question in which one of the response contained the following LINQ code:

var selected = lstAvailableColors.Cast<ListItem>().Where(i => i.Selected).ToList();
selected.ForEach( x => { lstSelectedColors.Items.Add(x); });
selected.ForEach( x => { lstAvailableColors.Items.Remove(x);});

Can someone explain the above LINQ to a total newbie?

解决方案

The LINQ operators use what's called a fluent interface, so you can read the first line as a series of function calls. Assuming that lstAvailableColors is IEnumerable<T>, the idea is that each available color flows through the LINQ operators.

Let's break it down:

var selected = lstAvailableColors
    // each item is cast to ListItem type
    .Cast<ListItem>() 
    // items that don't pass the test (Selected == true) are dropped
    .Where(i => i.Selected) 
    // turn the stream into a List<ListItem> object
    .ToList();

EDIT: As JaredPar pointed out, the last line above (ToList()) is very important. If you didn't do this, then each of the two selected.ForEach calls would re-run the query. This is called deferred execution and is an important part of LINQ.

You could rewrite this first line like this:

var selected = new List<ListItem>();

foreach (var item in lstAvailableColors)
{
    var listItem = (ListItem)item;

    if (!listItem.Selected)
         continue;

    selected.Add(listItem);
}

The last two lines are just another way to write a foreach loop and could be rewritten as:

foreach (var x in selected)
{
    lstSelectedColors.Items.Add(x);
}

foreach (var x in selected)
{
    lstAvailableColors.Items.Remove(X);
}

Probably the hardest part of learning LINQ is learning the flow of data and the syntax of lambda expressions.

这篇关于解释这种LINQ code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆