List사용하지 않고 C #에서 다른 항목을 포함하는 항목을 어떻게 전송 foreach합니까?
답변
당신은 이것을 시도 할 수 있습니다 :
List<Int32> copy = new List<Int32>(original);
또는 Linq와 함께 C # 3 및 .NET 3.5를 사용하는 경우 다음을 수행 할 수 있습니다.
List<Int32> copy = original.ToList();
답변
한 목록의 내용을 이미 존재하는 다른 목록에 추가하려면 다음을 사용하십시오.
targetList.AddRange(sourceList);
목록의 새 사본을 만들려면 Lasse의 답변을 참조하십시오.
답변
요소 목록
List<string> lstTest = new List<string>();
lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");
모든 요소를 복사하려면
List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);
처음 3 개 요소를 복사하려는 경우
List<string> lstNew = lstTest.GetRange(0, 3);
답변
그리고 이것은 단일 속성을 다른 목록으로 복사해야하는 경우입니다.
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
답변
이 방법을 사용하면 목록의 사본이 작성되지만 유형은 직렬화 가능해야합니다.
사용하다:
List<Student> lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList(); 
방법:
public static List<T> CopyList<T>(this List<T> lst)
    {
        List<T> lstCopy = new List<T>();
        foreach (var item in lst)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, item);
                stream.Position = 0;
                lstCopy.Add((T)formatter.Deserialize(stream));
            }
        }
        return lstCopy;
    }
답변
OK 이것은 잘 작동합니다. 위의 제안에서 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 );
}
답변
for 루프없이 linq로 다른 목록 세트를 쉽게 매핑
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();
