通过过滤和分组LINQ查询来获取数据

时间:2016-06-08 07:08:26

标签: c# oracle entity-framework linq

有人可以帮我编写代码以从分组和过滤的查询中获取数据吗?

数据来自简单的数据表,我需要的是如果用户只输入一个搜索参数,如何解决问题,还有可能输入更多的参数?

$row = mysqli_fetch_array($query));

for($i=0; $row = $result->fetch(); $i++){

           <tr>
                <td><?php echo $row['table4_id'];?></td>

                <td><?php echo $row['table3_id'];?></td>

                <td><?php echo $row['table2_id'];?></td>

                <td><?php echo $row['firstname'] . " " .$row['middlename'] . " " . $row['lastname'] . " " . $row['extension_name'];?></td>
            </tr>
       }

为了获得过滤后的数据我尝试过:

public class Journal
{
    public int ID {get; set;}
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

/*variables entered bu user:
searchParam1
searchParam2
...
searchParamN
*/

using (var dbContext = new databaseContext())
{
    var serchresult = dbContext.Journals
        .Where(p => p.Field1.StartsWith(SearchParam1) && 
                    p.Field2.StartsWith(SearchPParam2))
        .GroupBy(f => f.ID)
        .ToList();
}

但我需要添加分组:(

2 个答案:

答案 0 :(得分:1)

你快到了。将查询拆分为两部分。在第一部分中进行动态过滤,在第二部分中进行其余的操作。

var source = dbContext.Journals.AsQueryble();
if (!string.IsNullOrEmpty(SearchParam1))
    source = source.Where(tr => tr.Field1.StartsWith(SearchParam1));
if (!string.IsNullOrEmpty(SearchParam2))
    source = source.Where(tr => tr.Field2.StartsWith(SearchParam2));
var serchresult = source
      .GroupBy(f => f.ID)
      .ToList();

答案 1 :(得分:1)

你可以这样简化。

-(void)favoritePressed:(UIButton *)sender{
    //CustomCell : your custom UITableViewCell class name
    CustomCell *cell = (CustomCell) [[sender superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
}