Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an array of type T to an array of type I where T implements I in C#

I am trying to accomplish something in C# that I do easily in Java. But having some trouble. I have an undefined number of arrays of objects of type T. A implements an interface I. I need an array of I at the end that is the sum of all values from all the arrays. Assume no arrays will contain the same values.

This Java code works.

ArrayList<I> list = new ArrayList<I>();
for (Iterator<T[]> iterator = arrays.iterator(); iterator.hasNext();) {
    T[] arrayOfA = iterator.next();
    //Works like a charm
    list.addAll(Arrays.asList(arrayOfA));
}

return list.toArray(new T[list.size()]);

However this C# code doesn't:

List<I> list = new List<I>();
foreach (T[] arrayOfA in arrays)
{
    //Problem with this
    list.AddRange(new List<T>(arrayOfA));
    //Also doesn't work
    list.AddRange(new List<I>(arrayOfA));
}
return list.ToArray();

So it's obvious I need to somehow get the array of T[] into an IEnumerable<I> to add to the list but I'm not sure the best way to do this? Any suggestions?

EDIT: Developing in VS 2008 but needs to compile for .NET 2.0.

like image 307
Adrian Hope-Bailie Avatar asked Dec 03 '22 07:12

Adrian Hope-Bailie


1 Answers

Edited for 2.0; it can become:

static void Main() {
    IEnumerable<Foo[]> source = GetUndefinedNumberOfArraysOfObjectsOfTypeT();
    List<IFoo> list = new List<IFoo>();
    foreach (Foo[] foos in source) {
        foreach (IFoo foo in foos) {
            list.Add(foo);
        }
    }
    IFoo[] arr = list.ToArray();
}

How about (in .NET 3.5):

I[] arr = src.SelectMany(x => x).Cast<I>().ToArray();

To show this in context:

using System.Collections.Generic;
using System.Linq;
using System;
interface IFoo { }
class Foo : IFoo { //  A implements an interface I
    readonly int value;
    public Foo(int value) { this.value = value; }
    public override string ToString() { return value.ToString(); }
}
static class Program {
    static void Main() {
        // I have an undefined number of arrays of objects of type T
        IEnumerable<Foo[]> source=GetUndefinedNumberOfArraysOfObjectsOfTypeT();
        // I need an array of I at the end that is the sum of
        // all values from all the arrays. 
        IFoo[] arr = source.SelectMany(x => x).Cast<IFoo>().ToArray();
        foreach (IFoo foo in arr) {
            Console.WriteLine(foo);
        }
    }
    static IEnumerable<Foo[]> GetUndefinedNumberOfArraysOfObjectsOfTypeT() {
        yield return new[] { new Foo(1), new Foo(2), new Foo(3) };
        yield return new[] { new Foo(4), new Foo(5) };
    }
}
like image 166
Marc Gravell Avatar answered Dec 04 '22 21:12

Marc Gravell