0

我正在尝试找到一种更有效的方法来将附加信息从查询中添加到列表中。例如,如果我有一个包含 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;
    }
}

有没有办法将查询和赋值组合成一个语句?

4

2 回答 2

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
        }
}
于 2012-10-18T12:37:12.070 回答
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();
}

返回一个新列表而不更改原始列表只是个人喜好(最小化方法/函数的副作用)。

于 2012-10-18T18:20:45.793 回答