You could accomplish this through LINQ, however it should be noted that you'll need to create the objects to ensure the types match as expected (e.g. you cannot fill a list of LineItem objects with LineItemObjects) :
List<LineItemHelper> iLineItemHelper = iLineItem.Select(i => new LineItemHelper() { /* Add properties here */ })
.ToList();
Does that make sense? You would just need to map each property from your LineItem objects to their corresponding ones in your LineItemObject class.
class Program
{
static void Main(string[] args)
{
List<LineItem> lt = new List<LineItem>
{
new LineItem { A = 1, B = 2 },
new LineItem { A = 11, B = 22 },
new LineItem { A = 111, B = 222 }
};
Console.WriteLine();
foreach (LineItem p in lt)
{
Console.WriteLine(p.A + "****" + p.B);
}
List<LineItemHelper> lh = lt.ConvertAll(
new Converter<LineItem, LineItemHelper>(LineItemToLineItemHelper));
Console.WriteLine();
foreach (LineItemHelper p in lh)
{
Console.WriteLine(p.X + "****" + p.Y);
}
}
public static LineItemHelper LineItemToLineItemHelper(LineItem pf)
{
return new LineItemHelper(((int)pf.A), ((int)pf.B));
}
}
public class LineItemHelper
{
public LineItemHelper(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
}
public class LineItem
{
public int A { get; set; }
public int B { get; set; }
}
Member
51 Points
293 Posts
copy one list to another without foreach
Jan 26, 2016 09:00 PM|urpalshu|LINK
Hello:
Is there a way to copy one list to the other without foreach.
List<LineItemHelper> iLineItemHelper = new List<LineItemHelper>();
List<LineItem> iLineItem = new List<LineItem>();
iLineItemHelper = iLineItem; This does not work.
I need to copy iLineItem to iLineItemHelper.
Thank you
All-Star
114593 Points
18503 Posts
MVP
Re: copy one list to another without foreach
Jan 26, 2016 09:05 PM|Rion Williams|LINK
You could accomplish this through LINQ, however it should be noted that you'll need to create the objects to ensure the types match as expected (e.g. you cannot fill a list of LineItem objects with LineItemObjects) :
Does that make sense? You would just need to map each property from your LineItem objects to their corresponding ones in your LineItemObject class.
All-Star
17652 Points
3510 Posts
Re: copy one list to another without foreach
Jan 27, 2016 03:05 PM|Chris Zhao|LINK
Hi urpalshu,
Take a look at List<T>.ConvertAll<TOutput> Method (Converter<T, TOutput>)
Best Regards,
Chris Zhao