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?
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 multipleFirst()– 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, whereasSingle()has to scan the whole list, which could get a bit more expensive.Or you can use a where/select combo with null coalescing: