How to copy all at once without using foreach statement?

patrick

Well-known member
Joined
Dec 5, 2021
Messages
253
Programming Experience
1-3
How to copy all at once without using foreach statement?:
pulic class claList
{
    public string No;
    public string Name;
}

var copylist = new List<claList>;

foreach(claList lst in ret)
{
    var strList = new claList(); 
    strList.No = lst.No.Tostring();
    strList.Name = lst.Name.Tostring(); 
    copylist.Add(strList);
}

How to copy all at once without using foreach statement?
 
There will still be a loop in the execution but you can use LINQ to flatten code like this, e.g.
C#:
var copylist = ret.Select(cl => new claList {No = cl.No, Name = cl.Name}).ToList();
 
There will still be a loop in the execution but you can use LINQ to flatten code like this, e.g.
C#:
var copylist = ret.Select(cl => new claList {No = cl.No, Name = cl.Name}).ToList();

You gave sweet rain to the parched land.
Thank you so much for your reply.
 
Since our OP has declared claList as a POCO, the one line can be shortened some more:

C#:
var copylist = ret.Select(cl => cl.MemberwiseClone()).ToList();
 
Though @patrick, you should make sure to understand what MemberwiseClone does - the behavior will be subtly different on classes that have members that are reference types other than string. Consider providing a clone method on your objects, using a mapper that will do it, or making them immutable

Also, there's no point calling string.ToString(); it doesn't make a copy of the string, it just returns the same instance. There's no point copying strings because they aren't mutable, so you can't change the content of some string "John" assigned to this perosn/Name in a way that means that otherPerson.Name (also "John") sees the change.

Consider installing the roslynator Visual Studio Extension
 
Back
Top Bottom