Search code examples
c#linqobjectextension-methodsparent

Linq extension methods - how to obtain parent object?


My database looks like that: (it's pseudocode)

public class thread
{
   int id;
   List<Post> Posts;
}

public class Post
{
   int id;
}

As input, i have post id, and i want to know in what thread is that post. Can i do it with extension methods for linq?


Solution

  • I think you mean the following:

    var myThread = threads.FirstOrDefault(x => x.Posts.Any(p => p.id == somePostId));
    

    This would return the first (if any) matching thread instance which contains a post with the given post id or null if no instance matches. This assumes you have a collection threads of thread instances exposed e.g. using Linq to Entities.

    In general I would try to avoid class names that conflict with existing class names in the .NET framework (like Thread).