如何在select查询中添加函数

时间:2009-12-15 03:42:12

标签: c# linq function select

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"))

但我无法实现任何投入?

注意:类型转换需要处理空值(如果“description”没有值,则它(XElement)将完美地处理null。

1 个答案:

答案 0 :(得分:0)

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

// 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")
    };