zaria khan zaria khan - 26 days ago 9
C# Question

Get DISTINCT names

I am trying to use DISTINCT on my list

stationList
but it seems like I'm doing something wrong because I don't get distinct list. How would I get distinct ones in
Value
where I'm setting
stationList
.

foreach (StationCategory stationCategory in productCatalog.Programming.StationCategory)
{
StringBuilder stationList = new StringBuilder();
foreach (Station station in stationCategory.Station.Distinct())
{
stationList.Append(station.StationName + ",");
}
offer.FeatureList.Add(new Feature() { FeatureName = "<b>" + stationCategory.CategoryName + "</b>", Value = stationList.ToString().TrimEnd(',') });
}

Answer

Your current code does work, but it takes the distinct object references, instead of the names you expect. To do that, you have to tell the code how to match the Distinct.

There is a problem though, since Distinct doesn't take a lambda, so you can't say 'give me the distinct station names. In order to do that, you have to group, like in this sample:

var ds = stationCategory.Station.GroupBy(s => s.StationName)
                                .Select(g => g.FirstOrDefault());

ds now holds an enumerable of stations. You can take the name from it. The other properties are not guaranteed to be unique. (If you are only interested in the names, you could use this Select: .Select(g => g.FirstOrDefault()?.StationName);)