4

我正在尝试实现可以​​将结果填充到 Gridview 的搜索功能。我正在使用 LINQ 在 c# 中查询我的数据库。

我想弄清楚的问题是,如果用户想要通过多个搜索词搜索多个列/字段,那么我该怎么做呢?例如,如果我搜索包含这 3 个字段的表,并且我有一些数据,例如: > firstName | 姓氏 | 玩家# >>1. 迈克尔 | 约旦 | 12 >>2。迈克尔 | 约旦 | 24 >>3。迈克尔 | 约旦 | 45 >>4。德安德烈| 约旦 | 6 >> 5。杰罗姆| 约旦 | 44 >>6。约旦| 火花| 88

现在,如果我搜索 Jordan,我会得到所有信息:

如果我搜索迈克尔乔丹而不是我应该得到第 1、2、3 行。

如果我搜索 Jordan Sparks 88,我应该排在第 6 位。

所以我的问题是我不知道搜索词可能在表中的哪个位置,所以我必须搜索所有列/字段。在我当前的代码中,我有一些东西可以遍历每个列/字段名称并使用 Contains() 然后 || (“或”),但它仅适用于 1 个搜索词。

是否有一种优雅而简单的方法来搜索和过滤整个 linq 表,以便最小化列表?从那里我将该结果添加到数据源,然后绑定它。

@Sphinxxx 我正在使用典型的网格视图。它看起来像这样:

    <asp:GridView ID="GridView" runat="server" AllowSorting="True" PagerStyle-Mode="NumericPages"
                                AutoGenerateColumns="false" Width="100%" CssClass="gridView" OnPageIndexChanging="GridView_PageIndexChanging"
                                AllowPaging="True"  DataKeyNames="idPlayersList" OnRowCommand="GridView_RowCommand"
                                OnRowEditing="GridView_RowEditing" OnRowCancelingEdit="GridView_CancelEditRow"
                                OnRowUpdating="GridView_UpdateRow" OnRowDataBound="GridView_RowDataBound">
                                <RowStyle CssClass="rowStyle"></RowStyle>
                                    <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                                    <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="PlayersNumber" HeaderText="Players Number" SortExpression="PlayersNumber" />
<asp:TemplateField HeaderText="Team" SortExpression="Team">
                                    <EditItemTemplate>
                                        <asp:DropDownList ID="ddlTeam" runat="server" CssClass="dropdown" AutoPostBack="True"
                                            AppendDataBoundItems="true" DataTextField="TeamName" DataValueField="idTeam">
                                        </asp:DropDownList>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblTeam" runat="server" Text='<%# Bind("TeamName") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>

我当前的搜索功能如下所示:

/**
* This method is for button search functionality 
* 
*/
protected void btnSearch_Click(object sender, EventArgs e)
{

    // Call to Entity Model Framework
    DBModel.DBEntities context = new DBModel.DBEntities();
    
    string[] searchTerms = txtSearch.Text.Trim().Split('&');

//Prepare to build a "players" query:
IQueryable<DBModel.playersList> playersListQuery = context.playersLists;

foreach (var term in searchTerms)
{
    //Refine our query, one search term at a time:
    playersListQuery = playersListQuery.Where(p => p.isDeleted == false && (p.FirstName.Contains(term.Trim()) ||
                                           p.LastName.Contains(term.Trim()) ||
                                           p.PlayersNumber.Contains(term.Trim()) ||
                                           p.Team.Name.Contains(term.Trim())));
}

//Now we have the complete query. Get the results from the database:
var filteredplayersList = playersListQuery.Select(s => new
                                           {

                                               idPlayersList = s.idPlayersList,
                                               FirstName = s.FirstName,
                                               LastName = s.LastName,
                                               PlayersNumber  = s.PlayersNumber,
                                               TeamName  = s.Team.Name
                                            }).ToList();


GridView.DataSource = filteredplayersList; //Connecting query to the datasource Gridview
GridView.DataBind();  //Binding Gridview
}
4

2 回答 2

6

幸运的是,在 Linq2SQL 中创建多个 AND(每个搜索词一个)很容易 - 只需继续添加.Where(..到您的查询中:

string[] searchTerms = "Jordan Sparks 88".Split(' ');

using (var dc = new MyDataContext())
{
    //Using DataContext.Log is handy 
    //if we want to look at Linq2SQL's generated SQL:
    dc.Log = new System.IO.StringWriter();

    //Prepare to build a "players" query:
    IQueryable<Player> playersQuery = dc.Players;

    //Refine our query, one search term at a time:
    foreach (var term in searchTerms)
    {
        //Create (and use) a local variable of the search term
        //to avoid the "outer variable trap":
        //http://stackoverflow.com/questions/3416758
        //http://stackoverflow.com/questions/295593
        var currentTerm = term.Trim();
        playersQuery = playersQuery.Where(p => (p.isDeleted == false)
                                                &&
                                               (p.FirstName.Contains(currentTerm) ||
                                                p.LastName.Contains(currentTerm) ||
                                                p.PlayersNumber.Contains(currentTerm) ||
                                                p.Team.Name.Contains(currentTerm))
                                            );
    }

    //Now we have the complete query. Get the results from the database:
    var filteredPlayers = playersQuery.Select(p => new
                                                   {
                                                       p.idPlayer,
                                                       p.FirstName,
                                                       p.LastName,
                                                       p.PlayersNumber,
                                                       TeamName = p.Team.Name
                                                   })
                                      .ToArray();

    //See if the generated SQL looked like it was supposed to:
    var sql = dc.Log.ToString();
}
于 2013-07-01T23:38:11.010 回答
0

如果您只需要对所有属性使用 Contains 条件,您可以将所需的所有属性封装到一个中,然后您可以应用更少字段的 LINQ 表达式,它会看起来更干净。

public class Player
{
    public string SearchField { get => string.Format("{0}{1}{2}{3}",FirstName,LastName,PlayersNumber,Team); }

    public string FirstName {get; set;}

    public string LastName {get; set;}

    public string PlayersNumber {get; set;}

    public string Team {get; set;}
}

更好的是,我建议您在创建对象实例时在构造函数中设置 SearchField,这将提高性能,避免为每次调用创建子字符串。

public string SearchField { get; private set; }

public Player(string firstName, string lastName, playersNumber, string team)
{
    FirstName = firstName;
    LastName = lastName;
    PlayersNumber = playersNumber;
    Team = team;
    SearchField = string.Format("{0}{1}{2}{3}",firstName,lastName,playersNumber,team);
}

然后你只需按SearchField属性过滤

 foreach (var term in searchTerms)
 {
     var currentTerm = term.Trim();
     playersQuery = playersQuery.Where(p => p.isDeleted == false && 
                                            p.SearchField.Contains(currentTerm));
 }

现在您有了一个字段较少的 LINQ 表达式,可以得到完全相同的结果集。

我刚刚看到您提到您正在使用 LINQ to SQL 查询的另一件事,您可以通过在 SQL 表中创建一个连接多个列的值的计算列来应用相同的方法,您可以从 SQL Server 2012 开始执行此操作。

希望有人觉得这个解决方案有帮助。

问候!

于 2019-12-05T01:51:21.637 回答