返回匿名类型作为字符串linq的列表

时间:2012-03-07 15:13:54

标签: linq c#-4.0

我有一天......

这是我的班级:

/// <summary>
/// Represent a trimmed down version of the farms object for 
/// presenting in lists.
/// </summary>
public class PagedFarm
{
    /// <summary>
    /// Gets or sets Name.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Gets or sets Slug.
    /// </summary>
    public string Slug { get; set; }

    /// <summary>
    /// Gets or sets Rating.
    /// </summary>
    public int Rating { get; set; }

    /// <summary>
    /// Gets or sets City.
    /// </summary>
    public string City { get; set; }

    /// <summary>
    /// Gets or sets Crops.
    /// </summary>
    public List<string> Crops { get; set; }
}

这是我将父亲Farm实体解析为PagedFarm课程的微薄尝试。

    int pageNumber = page ?? 1;

    // Get a list of all the farms and hostels
    var farms =
        this.ReadOnlySession.Any<Farm>(x => x.Deleted == false).Select(
            x =>
            new PagedFarm
                {
                    Name = x.Name,
                    Slug = x.Slug,
                    Rating = x.Rating,
                    City = x.City.Name,
                    // The line below doesn't work.
                    Crops = x.Crops.Select(c => new { c.Name })
                    .OrderBy(c => c.Name)
                })
                .ToPagedList(pageNumber, this.PageSize);

我的错误讯息:

  

无法隐式转换类型   System.Linq.IOrderedEnumerable<AnonymousType#1>来   System.Collections.Generic.List<string>。显式转换   存在(你是否错过演员表?)

尝试铸造但没有快乐。我做错了什么?

2 个答案:

答案 0 :(得分:5)

我想你可能想要:

Crops = x.Crops.Select(c => c.Name).OrderBy(name => name).ToList()

答案 1 :(得分:3)

尝试:

Crops = x.Crops.Select(crop => crop.Name) // Sequence of strings
               .OrderBy(name => name)  // Ordered sequence of strings
               .ToList() // List of strings