I have below model classes
public class Hotel
{
public string hoteltype { get; set; }
public List<Room> rooms { get; set; }
}
public class Room
{
public Room2 room { get; set; }
public string name { get; set; }
}
public class Room2
{
public int number { get; set; }
public string category { get; set; }
public string subCategory { get; set; }
}
public class Root
{
public List<Hotel> hotels { get; set; }
}
Below is the JSON
{
"hotels": [
{
"hoteltype": "5star",
"rooms": [
{
"room": {
"number": 1,
"category": "Deluxe",
"subCategory": "type1"
},
"name": "xyz"
},
{
"room": {
"number": 2,
"category": "Deluxe",
"subCategory": "type2"
},
"name": "abc"
}
]
},
{
"hoteltype": "4star",
"rooms": [
{
"room": {
"number": 1,
"category": "Small",
"subCategory": "type1"
},
"name": "xyz"
},
{
"room": {
"number": 2,
"category": "Small",
"subCategory": "type4"
},
"name": "abc"
}
]
},
{
"hoteltype": "5star",
"rooms": [
{
"room": {
"number": 1,
"category": "Deluxe",
"subcategory": "type4"
},
"name": "xyz"
},
{
"room": {
"number": 2,
"category": "Deluxe",
"subcategory": "type5"
},
"name": "abc"
}
]
}
]
}
Expected Output:
{
"hotels": [
{
"hoteltype": "5star",
"rooms": [
{
"room": {
"number": 1,
"category": "Deluxe",
"subCategory": null
},
"name": "xyz"
},
{
"room": {
"number": 2,
"category": "Deluxe",
"subCategory": null
},
"name": "abc"
}
]
},
{
"hoteltype": "4star",
"rooms": [
{
"room": {
"number": 1,
"category": "Small",
"subCategory": null
},
"name": "xyz"
},
{
"room": {
"number": 2,
"category": "Small",
"subCategory": null
},
"name": "abc"
}
]
}
]
}
I’m trying to remove duplicates using LINQ – groupby and firstordefault. groupby should be on room – number and category but not on hoteltype. because we need combination of hoteltype, room number and category, if these three combinations are there in JSON that should be eliminated
Please suggest any solutions?
3
Answers
The Distinct() method exists entirely for this purpose.
You can either create a comparer or override Equals in Hotel, but I’ll give an example with the latter.
You will also have to write an equatable override for the rooms.
From your question you require a Linq GroupBy on
room => number, room => category
.This might be off, but might I suggest you change the Datatype of your Enumeration to HashSet hotels? Hashsets cannot have duplicates.