James South
James South

Reputation: 10645

returning anonymous type as list of string linq

I'm having one of those days....

Here's my class:

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

Here's my meagre attempt to parse my parent Farm entity into the PagedFarm class.

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

My error message:

Cannot implicitly convert type System.Linq.IOrderedEnumerable<AnonymousType#1> to System.Collections.Generic.List<string>. An explicit conversion exists (are you missing a cast?)

Tried casting but no joy. What am I doing wrong?

Upvotes: 1

Views: 3469

Answers (2)

Ani
Ani

Reputation: 113472

Try:

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

Upvotes: 3

devdigital
devdigital

Reputation: 34369

I think you probably want:

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

Upvotes: 5

Related Questions