如何在初始化列表之前获取查询中的值

时间:2018-05-28 10:25:47

标签: c# asp.net-mvc entity-framework

您好,我刚刚开始使用MVC i Entity Framework,我遇到了问题。 我可以在查询中获得Val4的价值吗? 我想我浪费时间两次初始化我的清单。

var query = from p in db.Table1
            join s in db.Table2 on p.ID equals s.sID
            join m in db.Table3 on s.sID equals m.ID
            group s by p into G
            select new Row
            {
                Val1 = G.Key,
                Val2 = G.Sum(x => x.someVal),
                Val3 = (from Z in db.Table4
                                 join p in db.Table5 on Z.ID equals p.ZamowienieID
                                 select p.otherVal).ToList().DefaultIfEmpty(0).Sum(),
                Val4 = 0,
            };

var list = query.ToList();

list.ForEach(x => x.Val4 = ((decimal)x.Val3 / (x.Val2 + (decimal)x.Val3)) * 100});

list = list.OrderbY(x =>x.Val4).ToList();

2 个答案:

答案 0 :(得分:5)

最好使用getter属性的Val4

public class Row
{
    public int Val1 { get; set; }

    public int Val2 { get; set; }

    public int Val3 { get; set; }

    public decimal Val4
    {
        get
        {
            return (decimal)Val3 / (Val2 + (decimal)Val3) *100;
        }
    }
}

查询看起来像;

var query = from p in db.Table1
            join s in db.Table2 on p.ID equals s.sID
            join m in db.Table3 on s.sID equals m.ID
            group s by p into G
            select new Row
            {
                Val1 = G.Key,
                Val2 = G.Sum(x => x.someVal),
                Val3 = (from Z in db.Table4
                                 join p in db.Table5 on Z.ID equals p.ZamowienieID
                                 select p.otherVal).ToList().DefaultIfEmpty(0).Sum()
            };
var result = query.ToList();

答案 1 :(得分:2)

是的,您可以,但不能直接在Row初始化程序中。

为了能够在Val3和投影中重复使用Val3Val4。如果您使用的是LINQ方法语法,则可以使用中间匿名投影(Select)。在查询语法中,您可以将let表达式用于相同的目的:

var query = from p in db.Table1
            join s in db.Table2 on p.ID equals s.sID
            join m in db.Table3 on s.sID equals m.ID
            group s by p into G
            let Val2 = G.Sum(x => x.someVal)
            let Val3 = (from Z in db.Table4
                        join p in db.Table5 on Z.ID equals p.ZamowienieID
                        select p.otherVal).DefaultIfEmpty(0).Sum()
            let Val4 = ((decimal)x.Val3 / (x.Val2 + (decimal)x.Val3)) * 100
            orderby Val4
            select new Row
            {
                Val1 = G.Key,
                Val2 = Val2,
                Val3 = Val3,
                Val4 = Val4,
            };