簡體   English   中英

LINQ:如何在 LINQ 查詢中添加多個變量?

[英]LINQ: how to add multiple variables to LINQ query?

我有一個名為 List 的 controller 動作,它采用以下參數

int Filer, int Field, int Operator, string QueryValue

public enum Filter
{
    ActiveEmployee,
    OnHoldEmployee,
    InactiveEmployee
}
public enum Field
{
    Name,
    ABRAID,
    JobTitle,
    LocationCode,
    Department
}
public enum Operator
{
    Contains,
    StartWith,
    EndWith,
    EqualTo
}

可能的情況:

Select employee where Name Equals "Value"

Select employee where Name EndWith with "Value"

Select employee where Name StartWith with "Value"

Select employee where JobTitle Contains "Value"

Select employee where Department Equals "Value"

我正在使用 LINQ 查詢數據庫

Employees = from p in DB.Employees
            where p.AWCID.Contains(queryvalue)
            select p;

但這意味着我必須使用嵌套的 switch 案例來涵蓋所有案例。 覆蓋 3 個變量的代碼超過 180 行,

我不太了解 LINQ 語法以支持多個值。

有什么想法嗎? 謝謝。

它確實使查詢復雜化。 如果使用實體框架,您可以考慮實體 SQL,因為您可以將整個查詢動態地構建為字符串,所以它的復雜性要低得多。 或者,LINQ 到 SQL 具有動態 LINQ,它還支持基於文本的查詢...

假設查詢將只是一種類型的查詢(包含,開始等),我會嘗試這樣的事情:

public IQueryable<Employee> GetEmployees(queryType, value)
{
    var Employees = from p in DB.Employees
            select p;

    // could use a switch statement here as well
    if (queryType == "contains")
        return Employees.where(e => e.contains(value));
    else if...
}

您還可以將查詢類型設為枚舉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM