C # Integrated IGrouping Initialization

If I want to initialize a grouping list, can I do this inline?

Context Update

I already know that I cannot initialize the interface, but is there an implementation already built into dotnet?

I don’t want to create my own implementation, because I am trying to reorganize an existing private method into my own class, which is publicly available, so I need to pass parameters for unit testing.

void MyMethod(IList<IGrouping<int, MyObject>> objGroupings)

Currently, I resorted to initializing the list and then grouping by key:

var fooList = new List<MyObject>
{
     new MyObject{ foo = 5 },
     new MyObject{ foo = 5 },
     new MyObject{ foo = 5 },
     new MyObject{ foo = 2 },
     new MyObject{ foo = 2 }
};

var fooGrouping = fooList.GroupBy(o => o.foo).ToList();
+4
source share
3 answers

IGrouping - . , , IGrouping

+6

@David Pilkington. , / :

sealed class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
    private readonly TKey m_key;
    private readonly IEnumerable<TElement> m_elements;

    public Grouping(TKey key, IEnumerable<TElement> elements)
    {
        if (elements == null)
            throw new ArgumentNullException("elements");

        m_key = key;
        m_elements = elements;
    }

    public TKey Key
    {
        get { return m_key; }
    }

    public IEnumerator<TElement> GetEnumerator()
    {
        return m_elements.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
+2

Instead, you can initialize the dictionary:

var dic = new Dictionary<string, int>()
{
    { "foo", 1 },
    { "bar", 2 },
};

If you belong to several values ​​with the same key, use a dictionary of list or values ​​(choose the type of list that will be more efficient for your code)

-2
source

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


All Articles