首先,阅读下面的类代码。在那里,您将找到一个名为CommonId的属性,该属性在Item类和ItemGallery中很常见,并且都具有匹配的int值。现在,检查作为主控制台程序的Program类。在这里,我将一些数据添加到两个类中以作为示例。在主程序类的底部,我尝试遍历每个Item并找到与ItemGallery commonId匹配的commonId,如果匹配的commonId则在ItemGallery中从其匹配的Item ID复制ItemId。主要目标是-只需将副本从Item类ID复制到具有相匹配commonId的ItemGallery ItemId。怎么做?我已经尝试过像波纹管一样的foreach,但这不是正确的方法。
主程序类:
class Program {
static void Main(string[] args) {
List<Item> MyItemList = new List<Item>();
MyItemList.Add(new Item {
CommonId = 502,
Id = 3,
Link = "some string1"
});
MyItemList.Add(new Item {
CommonId = 502,
Id = 4,
Link = "some string2"
});
MyItemList.Add(new Item {
CommonId = 502,
Id = 5,
Link = "some string3"
});
MyItemList.Add(new Item {
CommonId = 506,
Id = 6,
Link = "some string4"
});
List<ItemGallery> MyitemGalleries = new List<ItemGallery>();
MyitemGalleries.Add(new ItemGallery {
CommonId = 502,
Link = "",
});
MyitemGalleries.Add(new ItemGallery {
CommonId = 502,
Link = "",
});
MyitemGalleries.Add(new ItemGallery {
CommonId = 502,
Link = "",
});
foreach (var _MyItemList in MyItemList) {
MyitemGalleries.FirstOrDefault().ItemId = _MyItemList.Where(x => x.CommonId == MyitemGalleries.CommonId).FirstOrDefault().Id;
}
Console.ReadKey();
}
}
班级:
class Item {
public int Id { get; set; }//this id need to set to ItemGallery ItemId matching their CommonId
public int CommonId { get; set; }
public string Link { get; set; }
}
class ItemGallery {
public int ItemId { get; set; }
public int CommonId { get; set; }
public string Link { get; set; }
}
答案 0 :(得分:2)
如果我了解您并且不考虑任何其他问题,则没有几种方法可以做到这一点。但是,简单的foreach
和FirstOrDefault
应该可以
foreach (var gallery in MyitemGalleries)
{
var item = _MyItemList.FirstOrDefault(x => x.CommonId == gallery.CommonId);
// note if there are none we choose not to do anything, or grab the first
if(item == null)
continue;
gallery.ItemId = item.Id;
}