我正在尝试找到一种更有效的方法,以便从查询中向列表中添加其他信息。例如,如果我有一个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;
}
}
有没有办法将查询和赋值组合成一个语句?
答案 0 :(得分:1)
只需更新整个List
...
public void AddInformationToSomeObjects(IEnumerable<SomeObject> someObjects)
{
someObjects =
from obj in someObjects
join dbObj in db.Table
on obj.ObjectID equals dbObj.ObjectID
select new SomeObject
{
ObjectID = obj.ObjectID,
StringA = obj.StringA,
StringB = dbObj.StringB,
StringC = dbObj.StringC
}
}
答案 1 :(得分:0)
正如Jan P.所说,重新获取新名单可能不是什么大问题。但它获得第一个列表涉及一些昂贵的操作(如获取blob)你的想法一点也不差。简单的连接就是:
public List<SomeObject> 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();
return(
from org in someObjects
join a in informationToAdd on org.ObjectID equals a.ObjectID
select new SomeObject {
ObjectID = org.ObjectID,
StringA = org.StringA,
StringB = a.StringB,
StringC = a.StringC
}).ToList();
}
返回新列表而不更改原始列表只是个人偏好(最小化方法/功能的副作用)。