Frage

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

Update with context

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

I don't want to create my own implementation, because I am trying to refactor an existing private method into its own class which is public, thus I need to pass parameters in for unit testing.

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

Currently I have resorted to initializing a list, then grouping by a 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();

Keine korrekte Lösung

Andere Tipps

IGrouping is just an interface and cannot be initialised. If you want to use the inline initialisation, you need you initialise an object that implements IGrouping

I agree with @David Pilkington's answer. Here's a class I've written/used for this purpose in the past:

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();
    }
}

You can initialize a dictionary instead:

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

If you concern of multiple values with the same key, use dictionary of list or values (choose the list's type which be more efficient for your code)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top