I have a database table like this:
## Settings ##
ID (string)
Value (string)
The ID is a string like this Area.Category.SettingName.
I’m trying to build a menu structure based on the ID’s, so I would like it to be presented like this.
- Area
-- Category
--- SettingName
Data could be like this:
AreaOne.CategoryOne.MySetting
AreaOne.CategoryOne.MySecondSetting
AreaTwo.CategoryOne.MySetting
...
So to do this I tried to get all level one settings, and I tried that using this code:
List<Settings> settings = settings.GroupBy(x => x.ID.Split('.')[0]).FirstOrDefault().ToList()
And expected this result:
AreaOne
AreaTwo
But got this result:
AreaOne
AreaOne
AreaTwo
What am I doing wrong?
If all you want is the level one settings, the correct query would be
This cuts off the L1 setting from each row and uses
Distinctto make sure you only get each of them back once. There’s no need to useGroupByunless you want to get aggregate information about each L1 setting (for example, if you want to get full information back from the database but grouped on L1 setting name because it’s convenient for some reason).I also used the overload of
Splitthat takes a “limit” parameter because there’s no point in doing work that you are going to throw away.Finally, using a combination of
FirstIndexOfandSubstringwould be even better performance-wise.