我正在尝试找到一种更有效的方法来将附加信息从查询中添加到列表中。例如,如果我有一个包含 ObjectID 和 StringA 集合的对象列表,我想根据 ObjectID 查询数据库以检索 StringB 和 StringC:
public class SomeObject {
public int ObjectID { get; set; }
public string StringA { get; set; }
public string StringB { get; set; }
public string StringC { get; set; }
}
public void AddInformationToSomeObjects(List<SomeObject> someObjects)
{
var listOfIDs = someObjects.Select(so => so.ObjectID).ToList();
var informationToAdd = db.Table.Where(t => listOfIDs.Contains(t.ObjectID)).Select(t => new { ObjectID = t.ObjectID, StringB = t.StringB, StringC = t.StringC }).ToList();
foreach (var someObject in someObjects)
{
var information = informationToAdd.Where(i => i.ObjectID == someObject.ObjectID).FirstOrDefault();
someObject.StringB = information.StringB;
someObject.StringC = information.StringC;
}
}
有没有办法将查询和赋值组合成一个语句?