views:

96

answers:

1

I have the following Linq Expression

var tooDeep = shoppers
    .Where(x => x.Cart.CartSuppliers.First().Name == "Supplier1")
    .ToList();

I need to turn the name part into the following string.

x.Cart.CartSuppliers.Name

As part of this I turned the Expression into a string and then split on the . and removed the First() argument. However, when I get to CartSuppliers this returns a Suppliers[] array. Is there a way to get the single type from this. eg. I need to get a Supplier back.

Update: Got it to work

var fullName = m.ToString().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
// this supports the "deep graph" name - "Product.Address.City"
var fixedName = fullName.Skip(1).Take(fullName.Length - 1)
.Where(x => x != "First()")
.Select(x => System.Text.RegularExpressions.Regex.Replace(x, @"\[[0-9]+\]",""))
.ToArray();

with this:

var prop = property.PropertyType.HasElementType ? property.PropertyType.GetElementType()  property.PropertyType;

which enabled be to find the individual type from an array.

Thanks

+1  A: 
firstSupplierWithNeededName = shoppers
    .SelectMany(s => s.Cart.CartSuppliers)
    .First(s => s.Name == "Supplier1");

But also look into using FirstOrDefault or Single if it has to return just one.

Yuriy Faktorovich
I'm talking about parsing expression trees. I know the query can be written other ways but thats not the point.
Schotime
Can you add some more detail to your question?
Yuriy Faktorovich