Ahror Kayumov
Ahror Kayumov

Reputation: 453

c# selecting from list with lambda expression

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.

Upvotes: 2

Views: 5091

Answers (3)

Gilad Green
Gilad Green

Reputation: 37299

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;

Upvotes: 0

Mostafiz
Mostafiz

Reputation: 7352

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
 }

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

Try this,

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

Upvotes: 0

Related Questions