Define a list of objects. Get by a specific field in an object

How can we create a list of objects in C # and attach them to a specific field inside this object?

For example, take this object:

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

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

I would like to create a list of these objects that I can access with Section.Name.

I can create a dictionary like:

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 can see, I have to declare the name of the section twice, which looks inelegant. Is there a more elegant way?

+4
source share
5 answers

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

, ToDictionary call:

    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);
+2

, List<Section> list = new ArrayList<Section>(); .
  LINQ .where(x=>x.Name=="somename")

+2

, Model :

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

Name , :

private static List<Section> myList = new List<Section>();
myList.add(new Section {Name = "section-a", Size = 1});
// do this for all the sections ...

, , LINQ:

myList.Single(s => s.Name == "section-a");

, "section-a".

LINQ : https://msdn.microsoft.com/en-us/library/bb308959.aspx

+1

, . - :

public static Dictionary<string, Section> SectionDictionary(List<Section> sections) {
    var dict = new Dictionary<string, Section>();
    foreach (var section in sections)
        dict.Add(section.Name, section);
    return dict;
}
0

LINQ:

var list = ...;
var el = list.FirstOrDefault(o => o.Name = nameValue);

Or you can create a class (collection) that implements your own indexer / getter logic. For instance. (Pseudocode)

public class MyCollection : Collection<Section>
{
    public Section this[string nameValue]
    {
        get
        {
            return this.FirstOrDefault(o => o.Name == nameValue);
        }
    }
}

Then use:

var coll = new MyCollection() ....;
var el = coll["Some name"];
0
source

Source: https://habr.com/ru/post/1674070/


All Articles