不可能的concat没有为每个循环工作

Sur*_*rya 3 c# linq c#-4.0

我正在尝试在Concat每个循环中使用IEnumerable 的方法,但我无法使其正常工作.

IEnumerable<Geo> geos = null;
foreach (string a in values)
{
    if (geos == null)
        geos = entities.Geos.Where(g => (g.ACode == Convert.ToInt16(a)));
    else
        geos = geos.Concat(entities.Geos.Where(g => (g.ACode == Convert.ToInt16(a))));
}
Run Code Online (Sandbox Code Playgroud)

它返回的只是值中最终"a"的值,对于值中存在的记录计数也是如此.

因此,如果我有1,2,3作为值,它只返回3.我也需要1,2和3的值.

我哪里错了?

Sco*_*ain 6

您可能正在使用旧版本的C#,在C#5(随Visual Studio 2013提供)中他们改变了行为foreach.在C#4中,ain g => (g.ACode == Convert.ToInt16(a))foreachlazely评估时的最后一个值,在C#5和更新的时候它将始终是当前值.

要获得C#5行为,您只需要在foreach循环的范围内声明一个额外的变量,并在捕获中使用它.

IEnumerable<Geo> geos = null;
foreach (string a in values)
{
    string b = a;
    if (geos == null)
        geos = entities.Geos.Where(g => (g.ACode == Convert.ToInt16(b)));
    else
        geos = geos.Concat(entities.Geos.Where(g => (g.ACode == Convert.ToInt16(b))));
}
Run Code Online (Sandbox Code Playgroud)

如果你很好奇,改变的是在C#4中,你的原始代码将被翻译成

IEnumerable<Geo> geos = null;
using(IEnumerator<string> enumerator = values.GetEnumerator())
{
    string a;
    while(enumerator.MoveNext())
    {
        a = enumerator.Current;

        if (geos == null)
            geos = entities.Geos.Where(g => (g.ACode == Convert.ToInt16(a)));
        else
            geos = geos.Concat(entities.Geos.Where(g => (g.ACode == Convert.ToInt16(a))));
    }
}
Run Code Online (Sandbox Code Playgroud)

在C#5及更新版本中,它被翻译为

IEnumerable<Geo> geos = null;
using(IEnumerator<string> enumerator = values.GetEnumerator())
{
    while(enumerator.MoveNext())
    {
        string a = enumerator.Current;

        if (geos == null)
            geos = entities.Geos.Where(g => (g.ACode == Convert.ToInt16(a)));
        else
            geos = geos.Concat(entities.Geos.Where(g => (g.ACode == Convert.ToInt16(a))));
    }
}
Run Code Online (Sandbox Code Playgroud)

通过string b = a;在C#4中执行,我们重新创建了while循环内部的声明行为.