在Linq deferred linq语句中计算值

时间:2014-11-07 08:48:12

标签: c# linq

我正在尝试优化这段代码,这段代码大约需要50秒才能调用。这需要做的是从item.score获得总分,如果condition.isFound == false,则从item.score获得分数。你们给予的任何帮助都会很棒

var myscore = from inspection in roomInspections
            from RoomItemInspection in db.Table<RoomItemInspection>()
                where RoomItemInspection.roomInspectionId == inspection.id
            from RoomItemConditionInspection condition in db.Table<RoomItemConditionInspection>()
                where condition.roomItemInspectionId == RoomItemInspection.id
            from FloorRoom floorRoom in db.Table<FloorRoom>()
                where floorRoom.id == RoomItemInspection.roomItemId
            from room myRoom in db.Table<room>()
                where myRoom.id == floorRoom.roomId
            from RoomItem roomItem in db.Table<RoomItem>()
                where roomItem.roomId == myRoom.id
            from item myItem in db.Table<item>()
                where myItem.id == roomItem.itemId
            select new {score = myItem.Score, isFound = condition.isFound};

//This is the slow part of the code
totalScore = myscore.Sum (s => s.score);
        score = myscore.Sum (s => s.isFound ? s.score : 0);

        if(totalScore == 0)
            return 0;
        score = score / totalScore * 100f;
        return score = (float)Math.Round (score, 1);

以下是涉及的课程

public class room
{
    [PrimaryKey, AutoIncrement]
    public int PKId { get; set; }
    public int id { get; set; }
    public string name { get; set; }
    public DateTime dateCreated { get; set; }
    public DateTime dateModified { get; set; }
}

public class RoomItem
{
    [PrimaryKey, AutoIncrement]
    public int PKId { get; set; }
    public int id { get; set; }
    public int roomId { get; set; }
    public int itemId { get; set; }
    public bool isHidden { get; set; }
    public bool isAlways { get; set; }
    public DateTime dateCreated { get; set; }
    public DateTime dateModified { get; set; }
}

public class item
{
    [PrimaryKey, AutoIncrement]
    public int PKId { get; set; }
    public int id { get; set; }
    public string name { get; set; }
    public int Score { get; set; }
    public DateTime dateCreated { get; set; }
    public DateTime dateModified { get; set; }
}

public class RoomItemConditionInspection
{
    [PrimaryKey, AutoIncrement]
    public int PKId { get; set; }
    public int id { get; set; }
    public int conditionId { get; set; }
    public int roomItemInspectionId { get; set; }
    public bool isFound { get; set; }
    public bool isSynced { get; set; }
    public DateTime dateCreated { get; set; }
    public DateTime dateModified { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您应该使用PK,FK或索引加入字段。在您的代码中,您通过简单的字段进行连接,没有索引,这样就可以完全扫描表的decart乘法