Reputation: 63
I am stuck in converting a normal list to tree type list. I have to convert like below format: Can we create a list of parent child relationship?
State
County
Name
Name2
County
Name3
Name4
And below is my list :
{
"data": [
{
"name": "D1",
"stateName": "Georgia",
"stateId": 1,
"countyName": "Apache",
"countyId": 1
},
{
"name": "D2",
"stateName": "Georgia",
"stateId": 1,
"countyName": "Apache",
"countyId": 1
},
{
"name": "D3",
"stateName": "Georgia",
"stateId": 1,
"countyName": "Apache",
"countyId": 1
},
{
"name": "D4",
"stateName": "Georgia",
"stateId": 1,
"countyName": "Apache",
"countyId": 1
},
{
"name": "D5",
"stateName": "Georgia",
"stateId": 1,
"countyName": "Catron",
"countyId": 2
}
],
"totalRowCount": 0,
"errors": []
}
Is there any way that I can have tree list. Any help will be appreciated.
I am using below code for tree list but it is not giving me right data.
var lstTaxLocation = (from loc in _queryEntities.TaxLocations
join st in _queryEntities.States on loc.StateId equals st.Id
join cou in _queryEntities.Counties on loc.CountyId equals cou.Id
group new { loc, st, cou } by new { st.Id } into pg
let datagroup = pg.FirstOrDefault()
let location = datagroup.loc
let state = datagroup.st
let county = datagroup.cou
select new TaxLocationDto
{
Name = location.Name,
StateId = state.Id,
StateName = state.Name,
CountyName = county.Name,
CountyId = county.Id
});
Upvotes: 1
Views: 80
Reputation: 12805
This is very simple to do with LINQ.
Suppose you have your data already deserialized into C# objects:
public class Data
{
public string Name { get; set; }
public string StateName { get; set; }
public int StateId { get; set; }
public string CountyName { get; set; }
public int CountyId { get; set; }
}
You can then use LINQ's GroupBy
and SelectMany
.
var treeList = data.GroupBy(d => d.StateName)
.SelectMany(group => group.GroupBy(d => d.CountyName));
This will give you the structure you're looking for, but each "node" will be the entire object, not just the Name
property. You can get that as well if need be, but having the entire object there will most likely help more than just a single property.
Upvotes: 1