如何将 Lambda 表达式翻译成普通的代码?c#

huangapple go评论85阅读模式
英文:

How to translate a lambda expression to normal code? c#

问题

我需要在 .net Framework 2.0 中使用这段代码,但问题是这个版本不支持使用 labmdas(WHERE),有没有办法?

var serializer = new JavaScriptSerializer();
retorno = serializer.Deserialize<RespuestaCvt>(respuesta);

var soloServidores = new List<RespuestaCvt>();
foreach (var row in retorno.Rows)
{
    if (listaEstados.Contains(row.EstadoId) && listaTipos.Contains(row.TipoId))
    {
        soloServidores.Add(row);
    }
}
return soloServidores;
英文:

I need to use this code in .net Framework 2.0 but the problem is that labmdas(WHERE) can't be used in this version, is there a way?

var serializer = new JavaScriptSerializer();
retorno = serializer.Deserialize&lt;RespuestaCvt&gt;(respuesta);

var soloServidores = retorno.Rows.Where(x =&gt; listaEstados.Contains(x.EstadoId)).Where(x =&gt; listaTipos.Contains(x.TipoId)).ToList();
                                return soloServidores;

答案1

得分: 0

由于直到 C# 3 才引入 Lambda 表达式,所以您将不得不改变实际的行过滤方式。由于您正在返回 List<>,我们可以回到使用 LINQ 之前的方式进行操作:

var soloServidores = new List<TheRowType>();
foreach (var row in retorno.Rows)
{
    if (listaEstados.Contains(row.EstadoId) && listaTipos.Contains(row.TopiId))
        soloServidores.Add(row);
}
return soloServidores;

当然,您也可以选择较为繁琐的方式,将 Lambda 表达式提取到静态方法中,然后实现适当的 Where(...) 扩展......但是,如果您打算尝试从较新的语言版本中模拟 C# 特性,通常最好将您的项目迁移到较新的版本中。

英文:

Since Lambda expressions were not available until C# 3 you will have to change the way you do the actual row filtering. Since you're returning List&lt;&gt; we can just go back to the pre-LINQ way of doing things:

var soloServidores = new List&lt;TheRowType&gt;();
foreach (var row in retorno.Rows)
{
    if (listaEstados.Contains(row.EstadoId) &amp;&amp; listaTipos.Contains(x.TopiId))
        soloServidores.Add(row);
}
return soloServidores;

Of course you could do it the hard way and extract the lambda to a static method then implement a suitable Where(...) extension... but if you're going to try to emulate C# features from a later language version then you're usually better off migrating your project to that later version.

huangapple
  • 本文由 发表于 2020年10月14日 06:52:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64344235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定