user583126
user583126

Reputation: 701

get property using linq

this might be really simple, but just need some help in getting the syntax right! let's say i have 2 classes A, B.

class A 
{
    string empname;
    string id;
    Child[] ca;
}

class Child
{
    string id;
    string name;
}

class B 
{
    string empname;
    string id;
    Child[] cb;
}

i want to map ca.name to cb.name. condition is cb.id= ca.id. how to do this in linq? i tried the below way:

ca.name=b.Child.select(x=>x.id.Equals(ca.id)) //here how to map the name property?

Upvotes: 3

Views: 1002

Answers (5)

James Michael Hare
James Michael Hare

Reputation: 38397

What do you mean when you say map? You want the name where the property are equal? Your classes seem to be a bit off in terms of access specification from your example, and from your example not sure if your array name is really cb or Child, I'll assume Child, but correct as necessary...

Basically there are several choices:

  • Single() - returns one and only one and throws if none or multiple.

  • SingleOrDefault() - returns one if exists, default if not, and throws if multiple

  • First() - returns first one if exists and throws if not.

  • FirstOrDefault() - returns first one if exists, default if not.

All of these have a predicate overload so you don't need a where clause. If you already know your item is unique, I'd recommend FirstOrDefault() since it stops after it finds it, whereas Single() has to scan the whole list, which could get a bit more expensive.

var item = b.Child.FirstOrDefault(x => x.id == ca.id);

if (item != null)
{
  ca.name = item.name;
}

Or you can use a where/select combo with null coalescing:

var name = b.Child.Where(x => x.id == ca.id)
       .Select(x => x.name)
       .FirstOrDefault() ?? "unknown";

Upvotes: 2

StephenA
StephenA

Reputation: 45

I'd probably do it this way:

var query = from innerItem in cb.cb
            where item.id.Equals(item.id)
            select innerItem;

if (query != null)
{
    item.name = query.Single().name;
}

Regards.

Upvotes: 1

Alex
Alex

Reputation: 2468

Use join clause:

var pairs=
    from a in ca    
    join b in cb on a.id equals b.id
    select new {a, b};

Upvotes: 0

dexter
dexter

Reputation: 7203

Uhm, unless I'm misunderstanding your question, the answer is pretty trivial:

     ca.name=b.Child.Where(x=>x.id.Equals(ca.id)).SingleOrDefault().Name; 

Upvotes: 0

sehe
sehe

Reputation: 392833

You probably want Where instead of Select

Upvotes: 2

Related Questions