envyM6 envyM6 - 1 year ago 54
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
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
which will only contain
city names from the JSON without any repetition.
i.e. Dubai appears three times in the JSON.

Any ideas?

Answer Source

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();