【问题标题】:How to add items in dictionary in which value is list of class?如何在字典中添加值是类列表的项目?
【发布时间】: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&lt;Coordinates&gt;(){yourCoorDinates}&gt;
  • Coordinates.Add(regionId, Coordinates.Where(ed =&gt; (ed.Key == regionId)).ToList());
  • 顺便说一句,最好将您的班级命名为Coordinate,否则可能会使您和其他人混淆班级本身是多个坐标的列表。
  • @Learning - 这不起作用吗? Coordinates.Add(regionId, Coordinates.Where(ed =&gt; (ed.Key == regionId)).ToList()) 其中Cordinates in Coordinates.Whe.. 是列表 List of Class not enum
  • @Developer:好的,让我试试你发布的内容。谢谢 :)

标签: c# .net linq


【解决方案1】:

假设你的班级名称是Coordinate,你的字典是Coordinates

基本上:

Coordinates.Add(
  new List<Coordinate>()
  { 
    new Coordinate()
    {
      Id = coordinateId
    }
  }
); //You can remove all the whitespaace

问题是这样的(因为您的代码检查字典中是否已经存在该键的列表)您的列表中始终只有 1 个条目。

那么为什么不改成Dictionary&lt;string, Coordinates&gt;呢?

在 json 术语中:

this is what you do:
{  "key" : [Coordinate] }

why not?
{  "key" : Coordinate }

Or are you trying to achieve? 
{  "key" : [Coordinate, Coordinate, Coordinate] }

答案更新

所以你做,想要后者:{ "key" : [Coordinate, Coordinate, Coordinate] }

您在每个字典条目中都有一个列表。如果字典是键和值的列表,则在一维中说字典中的列表是一个二维数组。

事情就在这里。您需要将其分解为 2 个步骤:

  1. 检查 regionId 键是否已经存在于字典中(这意味着已经存在 1 个坐标(
  2. 如果不是:使用第一个坐标创建一个新列表。
  3. 如果存在,请检查 CoordinateId 是否已存在,如果不存在,则将其添加到列表中。

解决方案

public string MyMethod(string coordinateId, string regionId)
{
    if (!Coordinates.ContainsKey(regionId))
    {
        oordinates.Add(regionId, new Coordinate() {Id = regionId});
    }
    else
    {
        //Get the list of coordinates out of the dictionary for its region
        var list = Coordinates[regionId];
        if(list.Any(cor=> cor.Id == coordinateId))
        {   //Check if any of the coordinates have the same Id
            return "This coordinate id already exist for this region id";

        } else
        {  //Otherwise we add it to the list.
            lists.Add(new Coordinate() { Id = regionId})
        }

    }
    return "added";
}

【讨论】:

  • 您能否发布一些与您更新的答案相关的代码,因为我从未使用过这种结构与字典
  • @Learning,我做到了,但我不应该这样做。您需要了解这些基本内容,而不仅仅是复制粘贴。
【解决方案2】:

使用正确的数据结构,Dictionary&lt;string, HashSet&lt;Coordinates&gt;&gt;Add the Equals and GetHashCode 方法到 Coordinates 在 id 上进行比较。

这样你就可以add another object to the HashSet,它只会在它不存在的情况下被添加。

【讨论】:

  • 您能否发布一些与您所说的内容相关的代码。以便通过参考我可以尝试一些东西
  • 添加了几个链接。
【解决方案3】:

试试这样的: Coordinates.Add(regionId, new List&lt;Coordinates&gt; { new Coordinates { Id = id, Range = ??? } });

【讨论】:

    【解决方案4】:

    我想你正在寻找这个:

    Coordinates.Add(regionId, new List<Coordinates>()
                            {
                              new Coordinates(){Id=1,range=10},
                              new Coordinates(){Id=2,range=110},
                              new Coordinates(){Id=3,range=1140}
                           });
    

    如果你想初始化这样的字典意味着你可以这样做:

    Dictionary<string, List<Coordinates>> Coordinates = new Dictionary<string, List<Coordinates>>()
    { 
        {"ID1", new List<Coordinates>()
              {
                new Coordinates(){Id=1,range=10},
                new Coordinates(){Id=2,range=110},
                new Coordinates(){Id=3,range=1140}
              }
        },
        {"ID2", new List<Coordinates>()
              {
                new Coordinates(){Id=1,range=10},
                new Coordinates(){Id=2,range=110},
                new Coordinates(){Id=3,range=1140}
              }
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2013-02-06
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      相关资源
      最近更新 更多