helloworld
helloworld

Reputation: 93

Getting the last Item of an collection

public class Author  
{ 
    public int Id {set;get;}

    [Required]
    public string Name { set; get; }

    public ICollection<Column> Columns {set;get;}

    public virtual File AuthorImage { set; get; }

}

I have above model. and I want to get all the authors and 1 Column for each. But I want the latest (last inserted id) column that per each.

Using DbContext, imagine I have DbSet<Author> Authors. What would be the correct linq for to get this?

for one Author, a LINQ query that returns the Column with the highest Id

Upvotes: 0

Views: 3268

Answers (2)

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

I think this is what you're looking for:

var authors = yourSet.Select(a => 
    new Author { Id = a.Id, Name = a.Name, Columns = new[]{a.Columns.Last()}, 
                 AuthorImage = a.AuthorImage});

This has the disadvantage of remaking every author, but what can you do.

Upvotes: 1

zigdawgydawg
zigdawgydawg

Reputation: 2046

For one author, this finds the Column with the highest Id:

if (author.Columns != null && author.Columns.Count > 0) 
{
    Column c = author.Columns.OrderByDescending(x => x.Id).First();
}

Upvotes: 2

Related Questions