envyM6 envyM6 - 2 months ago 13
C# Question

Creating Distinct Item List from a JSON

I've got a JSON as follows-

[
{
"From": "London",
"To": "Dubai",
"Duration": "4"
},
{
"From": "Dubai",
"To": "Mumbai",
"Duration": "8"
},
{
"From": "Dubai",
"To": "Dhaka",
"Duration": "4"
}
]


As you can see JSON has locations in
To
and
From
field. I'm creating the JSON using

List<model> list = new List<model>();

foreach (var item in lines)
{

string[] fields = item.Split(',');
list.Add(new model
{
From = fields[0],
To = fields[1],
Duration = fields[2]
});
}
var json = JsonConvert.SerializeObject(list, Formatting.Indented);


And the Model class

public class model
{
public string From { get; set; }

public string To { get; set; }
public string Duration { get; set; }
}


And finally I want to create a
List<string>
called
Cities
which will only contain
Distinct
city names from the JSON without any repetition.
i.e. Dubai appears three times in the JSON.

Any ideas?

Answer

I'm not certain if you mean the json directly, or the parsed list. Assuming that you meant the list, you can select the distinct elements that you need from your list using Linq:

var cities = list.Select(x => x.To).Distinct();