Sub select in LINQ

A

ArunDhaJ

Hi,
I'm trying to write a sub select in linq to generete the list of
users.

I have an XML like this:

<?xml version="1.0" encoding="utf-8"?>
<UserConfig>
<Users>
<User id="1" loginId="arun" firstName="Arunkumar"
lastName="Dharuman" >
<assignedRoles>
<id>1</id>
</assignedRoles>
</User>
<User id="2" loginId="arun" firstName="Arunkumar"
lastName="Dharuman" >
<assignedRoles>
<id>1</id>
<id>2</id>
</assignedRoles>
</User>
<User id="3" loginId="arun" firstName="Arunkumar1"
lastName="Dharuman1" >
<assignedRoles>
<assignedRoles>
<id>3</id>
<id>2</id>
</assignedRoles>
</assignedRoles>
</User>
</Users>
</UserConfig>

I'm following query works fine when assignedRole is ignored...

var users = from ul in xDoc.Descendants("User")
select new
{
Id = ul.Attribute("id"),
LoginName = ul.Attribute("loginId"),
FirstName = ul.Attribute("firstName"),
LastName = ul.Attribute("lastName"),
};

when trying to include assignedRole as

var users = from ul in xDoc.Descendants("User")
select new
{
Id = ul.Attribute("id"),
LoginName = ul.Attribute("loginId"),
FirstName = ul.Attribute("firstName"),
LastName = ul.Attribute("lastName"),
Roles = from ur in ul.Element
("assignedRoles")
select new
{
RoleId = ur.Element
("id")
};
};

so that the following code should work:

foreach (var user in users)
{
foreach(var role in Roles)
{
}
}

Regards,
ArunDhaJ
 
M

Martin Honnen

ArunDhaJ said:
<User id="2" loginId="arun" firstName="Arunkumar"
lastName="Dharuman" >
<assignedRoles>
<id>1</id>
<id>2</id>
</assignedRoles>
when trying to include assignedRole as

var users = from ul in xDoc.Descendants("User")
select new
{
Id = ul.Attribute("id"),

Are you sure you want to store the 'id' XAttribute? I would rather go
with Id = (int)ul.Attribute("id")
LoginName = ul.Attribute("loginId"),
FirstName = ul.Attribute("firstName"),
LastName = ul.Attribute("lastName"),
Roles = from ur in ul.Element
("assignedRoles")

I think you want
Roles = from rid in
ul.Element("assignedRoles").Elements("id")
select (int)rid

or if you want to create an anonymous type then
Roles = from rid in
ul.Element("assignedRoles").Elements("id")
select new { RoleId = (int)rid }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top