I have an array of accounts that are returned from our API that have the following data structure.
Accounts[] accounts = [
{
AccountNumber: 0000000001,
PrimaryPerson: Virginia,
PrimaryPersonNumber: 0001,
PersonRoleCode: "OWN",
PersonRoleDescription: "Owner",
RoleOrder: 1
PersonRoles: [
{
AccountRoleCode: "CO",
AccountRoleDescription: "Co-Owner",
PersonName: "David",
PersonNumber: 0002,
RoleOrder: 2
},
{
AccountRoleCode: "POA",
AccountRoleDescription: "Power of Attorney",
PersonName: "Clark",
PersonNumber: 0003,
RoleOrder: 6
}
]
},
{
AccountNumber: 0000000002,
PrimaryPerson: Clark,
PrimaryPersonNumber: 0003,
PersonRoleCode: "OWN",
PersonRoleDescription: "Owner",
RoleOrder: 1
PersonRoles: [
{
AccountRoleCode: "CO",
AccountRoleDescription: "Co-Owner",
PersonName: "Virginia",
PersonNumber: 0001,
RoleOrder: 2
},
{
AccountRoleCode: "POA",
AccountRoleDescription: "Power of Attorney",
PersonName: "David",
PersonNumber: 0002,
RoleOrder: 6
}
]
},
{
AccountNumber: 0000000003,
PrimaryPerson: David,
PrimaryPersonNumber: 0002,
PersonRoleCode: "OWN",
PersonRoleDescription: "Owner",
RoleOrder: 1
PersonRoles: [
{
AccountRoleCode: "CO",
AccountRoleDescription: "Co-Owner",
PersonName: "Clark",
PersonNumber: 0003,
RoleOrder: 2
},
{
AccountRoleCode: "CO",
AccountRoleDescription: "Co-Owner",
PersonName: "Virginia",
PersonNumber: 0001,
RoleOrder: 2
},
{
AccountRoleCode: "POA",
AccountRoleDescription: "Power of Attorney",
PersonName: "Virginia",
PersonNumber: 0001,
RoleOrder: 6
}
]
}
];
I need to sort this Accounts object based on the RoleOrder for the Accounts object itself, and the RoleOrder for the PersonRole object in each PersonRoles[] index.
I've tried to do it with LINQ, but I'm unsure why it's not working correctly.
Here's what I tried and what I expected it to do.
IEnumerable<Account> sortedAccounts = accounts
.OrderBy(acct => acct.PersonRoles
.Where(role => role.PersNbr == 0001)
.Select(x => x.RoleOrder)).ToList();
I expected it to order the main accounts[] by the PersonRoles[] where the PersNbr is equal to the given PersNbr (0001), and sort on the RoleOrder.
So basically I want to sort the accounts[] based on the RoleOrder for a specific person only.
So sorting based on Virginia will result in Accounts[] accounts = [0000000001, 0000000003, 0000000002]
Sorting based on David will result in Accounts[] accounts = [0000000003, 0000000001, 0000000002]
What I have for LINQ isn't doing anything (order remains the same), which makes me think I'm doing doing the query in the correct order.
How do I write a LINQ query to do this, or do I need to split it up into different queries?