我有一个专门为用户控件创建的结构。我的想法是我将拥有公共(public)属性(property) Guid Dictionary<string, Guid> Attachments
然后将其转换为我的私有(private) List<Attachment> attachments
在二传手上。我在这样做时遇到了麻烦,最好是使用 linq,但我对替代方案持开放态度。谢谢...
private List<Attachment> attachments;
public struct Attachment
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public Dictionary<string, Guid> Attachments
{
get { return attachments.ToDictionary(a => a.Name, a => a.Id); }
set { attachments = new List<Attachment> // not sure what to do here }
}
最佳答案
假设这是一个有效的设计(我还没有真正考虑过)我怀疑你想要:
attachments = value.Select(pair => new Attachment { Id = pair.Value,
Name = pair.Key })
.ToList();
不过,我强烈建议您不要使用可变结构。使用结构本身并不算太糟糕,但我会将其更改为:
public struct Attachment
{
private readonly Guid id;
private readonly String name;
public Guid Id { get { return id; } }
public string Name { get { return name; } }
public Attachment(Guid id, string name)
{
this.id = id;
this.name = name;
}
}
...此时转换只是:
attachments = value.Select(pair => new Attachment(pair.Value, pair.Key))
.ToList();
关于c# - 将字典转换为列表<struct>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019362/