CurlyFro
CurlyFro

Reputation: 1882

How to order parent object by child sub object

i have a List< PaperAbstract > class. a PaperAbstract class has a set of Authors. one of the Authors has a flag IsSubmitting true. how can i order my List< PaperAbstract > by the submitting authors LastName?

public class PaperAbstract
{
    public string Title { get; set; }
    public List<Author> Authors { get; set; }
}

public class Author
{
    public bool IsSubmitting { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

for example:

var paperAbstracts = new List<PaperAbstract>();
paperAbstracts.Add(new PaperAbstract
{
    Title = "Abstract 2",
    Authors = new List<Author>
    {
        new Author { IsSubmitting = false, FirstName = "F5", LastName = "L5"},
        new Author { IsSubmitting = true, FirstName = "F6", LastName = "L6"}
    }
});
paperAbstracts.Add(new PaperAbstract
{
    Title = "Abstract 3",
    Authors = new List<Author>
    {
        new Author { IsSubmitting = true, FirstName = "F1", LastName = "L1"},
        new Author { IsSubmitting = false, FirstName = "F2", LastName = "L2"}
    }
});
paperAbstracts.Add(new PaperAbstract
{
    Title = "Abstract 1",
    Authors = new List<Author>
    {
        new Author { IsSubmitting = false, FirstName = "F3", LastName = "L3"},
        new Author { IsSubmitting = true, FirstName = "F4", LastName = "L4"}
    }
});

the correct order of paperAbstracts should be Abstract 3, Abstract 1, Abstract 2.

Upvotes: 0

Views: 36

Answers (1)

cuongle
cuongle

Reputation: 75306

You can use OrderBy from LINQ:

 var result = input.OrderBy(x => x.Authors
                                  .First(a => a.IsSubmitting).LastName)

Upvotes: 1

Related Questions