1

I am doing this below - any better way to do this? converting one list to the other without creating new object?

DataContext c = new DataContext();
List<X> x=
context.X.Where(a => a.date>Datetime.Now>).ToList();            
        foreach(var a in x)
        {
            Y y= new Y();
            y.Name= a.Name;                
            c.Ys.InsertOnSubmit(y);
        }

        c.SubmitChanges();   
4

3 に答える 3

3

あなたは試すことができます:

var ys = context.X
                .Where(x => x.date > DateTime.Now)
                .Select(x => new Y { Name = x.Name });

c.Ys.InsertAllOnSubmit(ys);
于 2012-04-12T16:00:33.250 に答える
0

Not sure how much shortening would make it better. Maybe this would help:

You project into a list of Y so you don't have to create new Y's in your loop.

List<Y> list_of_ys =
context.X.Where(a => a.date>Datetime.Now)
         .Select(s => new Y(){Name=s.Name})
         .ToList()

foreach(var y in list_of_ys)
{        
   c.Ys.InsertOnSubmit(y);
}
于 2012-04-12T16:00:11.490 に答える