【问题标题】:Can I avoid this linq query redundancy?我可以避免这种 linq 查询冗余吗?
【发布时间】:2012-12-06 14:36:05
【问题描述】:

我的代码:

var myList = xDoc.Descendants("localita").Select(n => new
{
    ID = n.Element("id").Value.ToString(),
    Localita = n.Element("nome").Value.ToString(),
    Lat = n.Element("lat").Value.ToString(),
    Lng = n.Element("lon").Value.ToString(),
    MeteoOggi = new MeteoGiorno()
    {
        Min = n.Descendants("previsione").First().Element("temp_perc").Value.ToString(),
        Max = n.Descendants("previsione").First().Element("temp").Value.ToString(),
        DescrizioneTempo = n.Descendants("previsione").First().Element("desc_tempo").Value.ToString(),
        Precipitazioni = n.Descendants("previsione").First().Element("prec").Value.ToString(),
        VentoDirezione = n.Descendants("previsione").First().Element("v_dir").Value.ToString(),
        VentoIntensita = n.Descendants("previsione").First().Element("v_int").Value.ToString(),
        Pressione = n.Descendants("previsione").First().Element("press").Value.ToString(),
        ZeroTermico = n.Descendants("previsione").First().Element("zerot").Value.ToString(),
        Immagine = n.Descendants("previsione").First().Element("id_tempo").Value.ToString()
    }
});

但正如您所见,每次我为 MeteoGiorno 类设置值时,都会“搜索”n.Descendants("previsione").First()。我可以在我的示例中对该节点进行某种引用吗?

【问题讨论】:

    标签: c# .net linq linq-to-xml


    【解决方案1】:

    当然可以,只需更改Select

    var myList = xDoc.Descendants("localita").Select(n => {
       var previsione = n.Descendants("previsione").First();
    
       return new {
          ID = n.Element("id").Value.ToString(),
          ....
          MeteoOggi = new MeteoGiorno()
          {
              Min = previsione.Element("temp_perc").Value.ToString(),
              Max = previsione.Element("temp").Value.ToString(),
              ....
          }
       }
    });
    

    【讨论】:

    • 是的,但是我还必须保留第一块数据,它来自n :O
    • @markzzz - 没有区别。我只是没有复制您的代码所有。查看更新 - 更清楚了吗?
    • 这简直太棒了!谢谢! Linq 太强大了!
    猜你喜欢
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多