2

I have a list of my entities and I'm using Select to get some properties from my entity. My entity has a PrimaryContact property and this has a LastNameproperty. So If I use like this it's working fine

var b = items.Select(s => s[PropertyName]); //Property name is "PrimaryContact" it's fine.

but If I use "PrimaryContact.LastName" this is not working

var x = items.Select(s => s[PropertyName]); //Property name is "PrimaryContact.LastName" it's not working

PropertyName might be evrything: "PrimaryContact.LastName", "PrimaryContact.FirstName", "PrimaryContact.Address.City"

Could someone help me on that please.

6
  • question is updated Commented Aug 13, 2016 at 10:30
  • isn't any of the solution working ? Commented Aug 13, 2016 at 10:32
  • it'll work only for PrimaryContact.LastName Commented Aug 13, 2016 at 10:34
  • so what do you expect all the property like FirstName, City etc ? Commented Aug 13, 2016 at 10:35
  • 2
    @AhrorKayumov Accessing a property by name using indexer is not a standard "entity" operation. You'd better post the implementation of the indexer. Commented Aug 13, 2016 at 10:44

3 Answers 3

1

If you want only one items LastName then

var x = items.Select(s => s["PrimaryContact"]).FirstOrDefault().LastName;

And if you want all items Lastname as collection then

var x = items.Select(s => s["PrimaryContact"].LastName);

if you want all the property then first select with all the property then iterate over it

ar x = items.Select(s => s["PrimaryContact"]);

foreach(var p in x)
 {
    // P.FirstName
    // p.LastName
    // p.Address.City
 }
Sign up to request clarification or add additional context in comments.

3 Comments

why I cant use var x = items.Select(s => s["PrimaryContact.LastName"]);
because seems PrimaryContact.LastName not collection of last name its a single entity but PrimaryContact is collection so you can select them using linq, but why do you this my solution is not best way ?
because PropertyName might be anything in my case not only PrimaryContact. PrimaryContact, PrimaryContact.LastName (FirstName ...). Category, Category.Name...
0

Try this,

var x = items.Select(s => s["PrimaryContact"].LastName);

2 Comments

Unfortunately this will not compile because Select will return IEnumerable<HisEntity> and not a single one - so you cant]'t .LastName
@GiladGreen agreed
0

Select returns IEnumerable so if you want all the LastNames in items then:

var b = items.Select(s => s["PrimaryContact"].LastName);

Otherwise if you want only of one of them then after the Select use FirstOrDefault:

var b = items.Select(s => s["PrimaryContact"]).FirstOrDefault().LastName;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.