c# - 定义对象列表。通过对象中的特定字段获取

标签 c# oop

我们如何在 C# 中创建对象列表并通过该对象中的特定字段访问它们?

例如拿这个对象:

class Section
{
    public string Name { get; }
    public long Size { get; }

    public Section(string name, long size)
    {
        Name = name;
        Size = size;
    }
}

我想创建一个我可以通过 Section.Name 访问的这些对象的列表。

我可以像这样创建一个字典:

private static readonly Dictionary<string, Section> validSections = new Dictionary<string, Section>
    {
        { "section-a", new Section("section-a", 1) },
        { "section-b", new Section("section-b", 2) },
        { "section-c", new Section("section-c", 3) },
        { "section-d", new Section("section-d", 4) },
    };

但是如您所见,我必须声明两次节名,这看起来很不雅观。有没有更优雅的方式?

最佳答案

But as you see, I have to declare the section name twice, which looks inelegant. Is there a more elegant way?

为避免重复输入,您可以通过 ToDictionary 调用从部分集合创建字典:

    private static readonly Dictionary<string, Section> validSections = new[] {
        new Section("section-a", 1),
        new Section("section-b", 2),
        new Section("section-c", 3),
        new Section("section-d", 4)
    }.ToDictionary(s => s.Name);

关于c# - 定义对象列表。通过对象中的特定字段获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43227488/

相关文章:

c# - 如何使用 IL 改变盒装结构

c# - Include 的 Entity Framework 性能问题

javascript 哎呀。构造函数与原型(prototype)设计

oop - 什么时候应该在类中使用静态方法?有什么好处?

java - 这两个java语句有什么区别?

oop - 如何在 Haskell 中建模类层次结构?

c# - 使用 .NET XCC 库时如何设置 xcc.txn.compatible 属性的值?

C#应用程序破解

c# - AWS 的奇怪版本控制问题

c# - .NET Stream 类是否设计不当?