开发者

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;
    C开发者_如何学运维hild[] 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 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";


You probably want Where instead of Select


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.


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; 


Use join clause:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜