EF LINQ查询在哪里满足所有列表或数组

时间:2014-01-17 08:02:48

标签: c# linq entity-framework

我有这些数据:

class MyTableItem
{
    public long id { get; set; }
    public long listId { get; set; }
    public long listFieldValue { get; set; }
    public long parentId { get; set; }
}  

    var myData = new MyTableItem[]
        {
            new MyTableItem { id = 1, listId = 1, listFieldValue = 100, parentId = 1 },
            new MyTableItem { id = 2, listId = 2, listFieldValue = 130, parentId = 1 },
            new MyTableItem { id = 3, listId = 3, listFieldValue = 170, parentId = 1 },
            new MyTableItem { id = 4, listId = 4, listFieldValue = 170, parentId = 1 },

            new MyTableItem { id = 5, listId = 1, listFieldValue = 100, parentId = 2 },
            new MyTableItem { id = 6, listId = 2, listFieldValue = 130, parentId = 2 },
            new MyTableItem { id = 7, listId = 3, listFieldValue = 170, parentId = 2 },
            new MyTableItem { id = 8, listId = 4, listFieldValue = 270, parentId = 2 },
            ...(continue)
        };

    var myMatchConditions = new int?[][] //id, rangeTypeId(equal, more, less, between), from, to 
        { 
            new int?[] { 1, 1, 100, null }, 
            new int?[] { 2, 2, 125, null }, 
            new int?[] { 3, 3, null, 175 }, 
            new int?[] { 4, 4, 130, 180 }
            ...(can continue more)
        };

现在我需要知道哪个myData(groupBy parrentId)与我的条件匹配,
让我解释一下:

我想知道哪个parrent Id有listFieldValue where:

1)(listId == 1)&&(listFieldValue == 100)

2)(listId == 2)&&(listFieldValue> 125)

3)(listId == 3)&&(listFieldValue< 175)

4)((listId == 4)&&(listFieldValue> 130)&&(listFieldValue< 180))

必须返回(1)parrentId。

1 个答案:

答案 0 :(得分:0)

你去吧。解释在底部:

IEnumurable<MyTableItem> temp = myData ;
for (int i = 0; i < myMatchConditions.GetLength(0); i++)
{
    var conditionType = myMatchConditions[i,1];
    if (conditionType == 1)
    {
        temp = temp.Where(_ => _listFieldValue == myMatchConditions[i,2]);
    }
    else
    {
        if (conditionType == 2 || conditionType == 4)
        {

            temp = temp.Where(_ => _listFieldValue > myMatchConditions[i,2]);
        }

        if (conditionType == 3 || conditionType == 4)
        {
            temp = temp.Where(_ => _listFieldValue < myMatchConditions[i,3]);
        }
    }
}
  • 我使用的是IEnumurable<MyTableItem>,这意味着它是Linq,而不是Linq。我之所以选择它是因为您的myData不是EF表,而是一个简单的数组。
  • 我经历了所有&#34;行&#34;使用for,您可以使用foreach执行此操作,并添加Where子句以逐次过滤掉(实际过滤仅在您使用{ {1}}列表)
  • 我根据第二个单元格中的类型添加条件,如果类型是4 ...我添加了2和3类型规则...这使得4类型规则