提取列表<a> from List<tuple<a,b>&gt; without creating a copy?

时间:2018-06-05 13:32:02

标签: c# linq reference

Short version: I know that C# works mostly, using references but I was wondering if that's also the case if you try to extract a List<A> from a List<Tuple<A,B>> while leaving the original List intact.

Long version: I am working with a lot of data right now, which means I need to be especially careful not to accidentally create a hardcopy of my data. I wrote a method which returns a List<Tuple<A, List<B>>. Each B is supposed to reference one A (not the one that it is already connected to through the Tuple). I can find the right object in List<A> using the information already contained in each B, however I obviously can't duplicate the Data in A or my RAM might explode. If I execute a command on the IEnumerable that is returned when I use ListOfTuples.Select(x=>x.Item1); will that operate on the List<A> in my List<Tuple...> or on a hardcopy?

2 个答案:

答案 0 :(得分:1)

如果您可以更改使用代码以使用IReadOnlyList<T>而不是List<T>,那么编写一个将Tuple<T,U>转换为{{1}的类并不难}}:

IReadOnlyList<T>

然后您可以像这样使用它:

public sealed class TupleExtraction<T, U> : IReadOnlyList<T>
{
    readonly List<Tuple<T, U>> _list;

    public TupleExtraction(List<Tuple<T, U>> list)
    {
        _list = list;
    }

    public T this[int index] => _list[index].Item1;

    public int Count => _list.Count;

    public IEnumerator<T> GetEnumerator()
    {
        return _list.Select(item => item.Item1).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _list.Select(item => item.Item1).GetEnumerator();
    }
}

请注意,这不会复制基础列表。

答案 1 :(得分:0)

List<A> result = ListOfTuples.Select(x=>x.Item1).ToList()

当A是引用类型时,它会创建第二个A列表而不复制A元素。 当A是值类型时,它会创建第二个列表,其中包含A元素的副本