我有一个Category类的对象列表。
我还有MarketData类的另一个对象列表,其中包含Category类的实例作为其属性。
MarketData类:
class MarketData
{
private int id;
private Category business;
private Category location;
private string companyName;
private string mobileNum;
private string email;
}
如何在不使用foreach循环的情况下单行将Category类对象列表添加到MarketData列表中?
我不想要的foreach循环方法:
List<MarketData> marketDataList = new List<MarketData>();
List<Category> businessList = new List<Category>();
int i = 0;
foreach(Category item in businessList)
{
marketDataList[i].Business = item;
i++;
}
答案 0 :(得分:0)
单行,您可以使用Enumerable.Range()生成索引集合,并使用Linq
直接使用它来循环和分配。
List<MarketData> marketDataList = new List<MarketData>();
List<Category> businessList = new List<Category>();
// this a one liner formatted on many line for visibility reasons
Enumerable.Range(0, marketDataList.Count()) // generate a collection from 0 to Count
.ToList() // as a list
.ForEach(i => marketDataList[i].Business = businessList[i]); // for each index assign the value