将每个列表项复制到另一个列表项属性

时间:2013-10-30 12:13:22

标签: c# .net optimization

是否有一种简单的方法,最重要的是,更优化的方法来执行fowling代码:

class Chair{
    int numberOfLegs=4;
}

class House{
    Chair chair;
    String name="My Home";
}

// add chairs to each house
IList<Chair> chairs = new List<Chair>(10); // let us imagine that we have 10 different chairs...

// Code to replace:
IList<House> houses = new List<House>(chairs.Count());
for (int i = 0; i < houses.Count(); i++){
    houses[i].chair = chairs[i]
}

1 个答案:

答案 0 :(得分:5)

我自己的建议是将for替换为Linq

// Code to replace:
IList<Homes> homes = chairs.Select(c => new Home{ Chair = c}).ToList();

它比旧代码更快吗?

你有更好的主意吗?也许使用chairs.AsParallel