【发布时间】:2017-10-15 03:09:54
【问题描述】:
我有一本下面的字典:
Dictionary<string, List<Coordinates>> Coordinates = new Dictionary<string,List<Coordinates>>();
public class Coordinates
{
public int Id { get; set; }
public decimal range { get; set; }
//other properties
}
现在我正在尝试将坐标添加到我的字典中以获取特定区域 id,如果出现相同的坐标 id,那么我不想添加它。
下面是我的网络服务方法:
public string MyMethod(string coordinateId, string regionId)
{
var coordinates = Coordinates.Where(ed => (ed.Key == regionId)).SelectMany(ed => ed.Value).ToList();
var coordinatesExist = coordinates.Any(ed => ed.Id.ToString() == id);
if (!Coordinates.ContainsKey(regionId) && !coordinatesExist)
{
//here i want to add it but as it is list of my class i dont know how to add it
Coordinates.Add(regionId, ?????);
}
else
{
return "This coordinate id already exist for this region id";
}
}
我检查了下面的链接,但这些答案与字符串列表或数组有关,但与类列表无关:
c# dictionary How to add multiple values for single key?
How to add values to Dictionary with a list of dictionaries inside
样本数据:
Region Id = 100
Coordinate Id = 10,20,30
Region Id = 200
Coordinate Id = 10,20,30
- 第一次使用 RegionId = 100 和坐标 id =10 调用 Mymethod 然后我想在我的字典中有:Key = 100 , value = 10
- 第二次调用 Mymethod 与 RegionId = 100 和坐标 id =20 然后我想在我的字典中有:Key = 100 , value = 20
- 第三次调用 Mymethod,RegionId = 100,坐标 id =20,然后我想在我的字典中有: 我不想添加这个,因为 regionId = 100 已经存在 20 个坐标 id
【问题讨论】:
-
基本上
new List<Coordinates>(){yourCoorDinates}> -
是
Coordinates.Add(regionId, Coordinates.Where(ed => (ed.Key == regionId)).ToList()); -
顺便说一句,最好将您的班级命名为
Coordinate,否则可能会使您和其他人混淆班级本身是多个坐标的列表。 -
@Learning - 这不起作用吗?
Coordinates.Add(regionId, Coordinates.Where(ed => (ed.Key == regionId)).ToList())其中CordinatesinCoordinates.Whe..是列表 List of Class not enum -
@Developer:好的,让我试试你发布的内容。谢谢 :)