如何返回一个没有重复的属性的列表?

alp*_*lle 0 c# list unique hashset

我有一个从数据库中提取州和城市列表的方法.州是独一无二的,但该州可能有许多城市.我的方法目前所做的是将每个州和城市对作为单独的项目返回.我需要它做的是拥有许多城市的州.

目前退货

辛辛那提

哦 - 克利夫兰

哦,findlay

在印第安纳波利斯

我需要它返回

哦,辛辛那提,克利夫兰,芬德利

在印第安纳波利斯

模型

public class Location
{
    public string State { get; set; }
    public string city { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

REPOSITORY

public HashSet<Location> getlocation()
    {
        HashSet<Location> myHashset = new HashSet<Location>();

        const string storedProc = "someProc";

        dynamic locations;


        using (var conn = DbFactory.myConnection())
        {
            locations = conn.Query(storedProc, commandType: CommandType.StoredProcedure);

        }

        foreach (var location in locations)
        {

                myHashset.Add(new location{State = location.state,City = location.city});


        }
          return myHashset
    }
Run Code Online (Sandbox Code Playgroud)

fub*_*ubo 5

这应该做到这一点

var Result = myHashset.GroupBy(r => r.State)
        .Select(g => new Location
        {
            State = g.Key,
            city = String.Join(", ", g.Select(r => r.city))
        });
Run Code Online (Sandbox Code Playgroud)

也许你不想将它存储到一个新Location对象中.我会用一本词典

更新 - 字典

Dictionary<string,string> Result = myHashset.GroupBy(r => r.State)
.ToDictionary(g => g.Key, g => String.Join(", ", g.Select(r => r.city)));
Run Code Online (Sandbox Code Playgroud)