我如何在c#中不使用foreach将一个列表中包含的项目转移到另一个列表中?


当前回答

很容易映射不同的列表集由linq没有for循环

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

其他回答

你可以试试这个:

List<Int32> copy = new List<Int32>(original);

或者如果你使用c# 3和。net 3.5,使用Linq,你可以这样做:

List<Int32> copy = original.ToList();

我看到这个答案仍然得到了点赞。好吧,这里有一个秘密给你:上面的答案仍然是使用一个foreach。请不要再投票了。

public static List<string> GetClone(this List<string> source)
{
    return source.Select(item => (string)item.Clone()).ToList();
}

好的,这工作得很好 根据上面的建议,GetRange()不适合我使用列表作为参数…所以从上面的帖子中让事情变得甜蜜一点:(谢谢大家:)

/*  Where __strBuf is a string list used as a dumping ground for data  */
public List < string > pullStrLst( )
{
    List < string > lst;

    lst = __strBuf.GetRange( 0, __strBuf.Count );     

    __strBuf.Clear( );

    return( lst );
}

要将一个列表的内容添加到已经存在的另一个列表,您可以使用:

targetList.AddRange(sourceList);

如果您只是想创建一个列表的新副本,请参阅顶部的答案。

很容易映射不同的列表集由linq没有for循环

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();