代码之家  ›  专栏  ›  技术社区  ›  Timothy055

如何在select查询中添加函数

  •  2
  • Timothy055  · 技术社区  · 16 年前
    select new FeedResource
    { 
       Title = (string)details.Element("title"),  
       Host = (string)details.Element("link"),   
       Description = (string)details.Element("description"), 
       PublishedOn = (DateTime?)details.Element("pubDate"), 
       Generator = (string)details.Element("generator"),  
      Language = (string)details.Element("language")
    }
    

    在上面的代码中,我想将类型转换值传递给另一个函数, 例子

    Description = getValidDescription((string) details.Element("description"))
    

    注意:类型转换需要处理null值(即在“description”没有值的情况下),它(XElement)可以完美地处理null。

    1 回复  |  直到 12 年前
        1
  •  0
  •   Marc Gravell    16 年前

    为我工作很好;错误消息是什么?例子:

    // doesn't have to be static - just simpler for my test
    static string getValidDescription(string description)
    {
        // handle nulls safely (could return a default here)
        if (description == null) return null;
        // for example only...
        return CultureInfo.CurrentCulture.TextInfo
            .ToTitleCase(description);
    }
    
    var qry =
        from details in doc.Root.Elements("detail")
        select new FeedResource
        {
            Title = (string)details.Element("title"),
            Host = (string)details.Element("link"),
            Description = getValidDescription((string) details.Element("description")),
            PublishedOn = (DateTime?)details.Element("pubDate"),
            Generator = (string)details.Element("generator"),
            Language = (string)details.Element("language")
        };