Reputation: 449
I have a nested class hierarchy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Models
{
public class Document
{
public Document();
public Guid ID { get; set; }
public List<Order> Orders {get; set;}
}
public class Order
{
public Order();
public Guid ID { get; set; }
public List<OrderItem> OrderItems {get; set;}
}
public class OrderItem
{
public OrderItem();
public Guid ID { get; set; }
public String ProductName { get; set; }
public int Qty { get; set; }
}
}
The IDs are GUIDs. I need to search generically to an object with a specified GUID. I have been advised that one approach is to specify an interface against the class for this (see: SO Question). However since my class is generated, I prefer to not alter the class. So I want to investigate an approach using LINQ to Objects. I have also found this excellent SO post on this approach: LINQ to Objects SO post, but of course one needs to specify all the child classes in the query.
Optimistically I was hoping for "get me the object with the GUID of x". GUIDs are unique, so I felt I did not need to specify a pathway. However I guess this is not possible with LINQ???
EDIT: Updated code above. Apologies. I would like to extract An OrderItem with GUID= X
Upvotes: 0
Views: 737
Reputation: 21485
With the modified question, the code to search for all matching OrderItem
objects inside a list of documents would be like this:
List<Document> data = ...;
Guid guidToSearch = ...;
var orderItems = data.SelectMany(o => o.Orders)
.SelectMany(o => o.OrderItems)
.Where(o => o.ID == guidToSearch)
.ToList();
If you have just one document, not a list, you can skip the first SelectMany
call.
Upvotes: 1
Reputation: 21485
Assuming you have a collection of different objects like this:
List<object> data = new List<object>() { new Order { ID = ... }, new Document { ID = ... } };
then you could write code like this
var guidToSearch = ...;
var results = data.Where<dynamic>(o => o.ID == guidToSearch).ToList();
thre results
collection will now contain the matching objects.
Upvotes: 0