如何在不克隆的情况下复制List <T>

naw*_*fal 7 .net c# clone copy generic-list

也许我错过了一些微不足道的东西.我有几个,List<T>我需要一个大的列表,这是所有其他列表的联合.但我确实希望他们在那个大名单中引用而不仅仅是值/副本(不像我通常在SO上找到的许多问题).

比如我有这个,

List<string> list1 = new List<string> { "a", "b", "c" };
List<string> list2 = new List<string> { "1", "2", "3" };

var unionList = GetThatList(list1, list2);
Run Code Online (Sandbox Code Playgroud)

假设我得到了我想要的列表unionList,那么这应该发生:

unionList.Remove("a"); => list1.Remove("a");
unionList.Remove("1"); => list2.Remove("1");

//in other words
//
//unionList.Count = 4;
//list1.Count = 2;
//list2.Count = 2;
Run Code Online (Sandbox Code Playgroud)

为了说清楚,这通常发生在

unionList = list1; //got the reference copy.
Run Code Online (Sandbox Code Playgroud)

但是如何list2添加第二个列表unionList

我尝试了Add,AddRange但他们显然克隆而不是复制.

unionList = list1;
unionList.AddRange(list2); //-- error, clones, not copies here.
Run Code Online (Sandbox Code Playgroud)

foreach (var item in list2)
{
    unionList.Add(item); //-- error, clones, not copies here.
}
Run Code Online (Sandbox Code Playgroud)

更新:我想我会问一些没有意义的东西,以及在语言中本来就不可能的东西......

Mar*_*ers 12

我不认为任何这样的类存在.你可以自己实现它.这是一个开始:

class CombinedLists<T> : IEnumerable<T> // Add more interfaces here.
                                        // Maybe IList<T>, but how should it work?
{
    private List<List<T>> lists = new List<List<T>>();

    public void AddList(List<T> list)
    {
        lists.Add(list);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return lists.SelectMany(x => x).GetEnumerator();
    }

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

    public bool Remove(T t)
    {
        foreach (List<T> list in lists)
        {
            if (list.Remove(t)) { return true; }
        }
        return false;
    }

    // Implement the other methods.
}
Run Code Online (Sandbox Code Playgroud)

以下是您可以用来测试它的一些代码:

List<string> list1 = new List<string> { "a", "b", "c" };
List<string> list2 = new List<string> { "1", "2", "3" };
CombinedLists<string> c = new CombinedLists<string>();
c.AddList(list1);
c.AddList(list2);

c.Remove("a");
c.Remove("1");

foreach (var x in c) { Console.WriteLine(x); }
Console.WriteLine(list1.Count);
Console.WriteLine(list2.Count);
Run Code Online (Sandbox Code Playgroud)

删除项目非常简单.但是,如果您尝试将项目插入组合列表,则可能会出现问题.并不总是明确定义哪个列表应该接收插入的项目.例如,如果您有一个包含两个空列表的组合列表,并且您在索引0处插入了一个项目,那么该项目是否应该添加到第一个或第二个空列表中?

  • @nawfal我很好奇.如果要添加项目怎么办? (3认同)