【问题标题】:Fill array of objects from ConcurrentDictionary从 ConcurrentDictionary 填充对象数组
【发布时间】:2020-07-26 13:16:39
【问题描述】:

我的 ConcurrentDictionary 如下代码:

public ConcurrentDictionary<long, User> Users { get; set; }

用户类别:

public partial class User
    {
        [JsonProperty("parentId")]
        public long ParentId { get; set; }

        [JsonProperty("firstName")]
        public string FirstName { get; set; }

        [JsonProperty("userType")]
        public long UserType { get; set; }

        [JsonProperty("accountId")]
        public long AccountId { get; set; }

        [JsonProperty("userName")]
        public string UserName { get; set; }

        [JsonProperty("id")]
        public long Id { get; set; }
    }

和数组如下代码: public Node[] Data { get; set; }

节点类:

public partial class Node
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("parent")]
        public long Parent { get; set; }

        [JsonProperty("text")]
        public string Text { get; set; }

        [JsonProperty("state", NullValueHandling = NullValueHandling.Ignore)]
        public State State { get; set; }

        [JsonProperty("icon")]
        public Uri Icon { get; set; }
    }

我需要将 User 对象从 ConcurrentDictionary 复制到一个 Node 对象数组中,所以应该将 User 对象的一些属性移动到 Node 对象中:

Node[] Data = new Node[]
{
  Id = user.Id,
  Parent = user.ParentId,
  Text = user.FirstName
}

有没有办法在不循环的情况下做到这一点,谢谢。

【问题讨论】:

  • 为什么Parent 是字符串而Text Node 类中很长?必须与User 具有相同的类型?
  • 谢谢,哥们,我已经修改了;)。

标签: c# .net linq .net-core


【解决方案1】:

你可以使用Linq

  1. 从字典中取值
  2. 通过将一些属性从User 转换为Node 来选择新的Node
  3. .ToArray()IEnumerable 转换为Array,如以下代码:
Node[] Data = Users.Values
    .Select(x => new Node { Id = x.Id, Parent = x.ParentId, Text = x.FirstName })
    .ToArray();

希望对你有所帮助。

【讨论】:

  • @AmmarSaleh:你能检查我的答案吗?
  • 我会检查并告诉你。
猜你喜欢
  • 1970-01-01
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2019-01-15
相关资源
最近更新 更多