英文:
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<RespuestaCvt>(respuesta);
var soloServidores = retorno.Rows.Where(x => listaEstados.Contains(x.EstadoId)).Where(x => 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<>
we can just go back to the pre-LINQ way of doing things:
var soloServidores = new List<TheRowType>();
foreach (var row in retorno.Rows)
{
if (listaEstados.Contains(row.EstadoId) && 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论