我有这个查询
public IEnumerable<TimesheetModel> FilterByUserId(IEnumerable<TimesheetModel> obj, int FilterUserId)
{
var query = (from list in obj.Where(x => x.List.Where(x => x.UserId.Equals(FilterUserId)))
select new TimesheetModel
{
TaskDate = list.TaskDate,
List = list.List
}).ToList();
return query;
}
我有错误:
无法在此范围内声明名为“x”的局部变量,因为它 会给'x'赋予不同的含义,它已经在a中使用了 “父母或当前”范围表示其他内容。
为什么我有这个错误以及如何解决这个问题?
我有这个模型
public class TimesheetModel
{
public DateTime TaskDate { get; set; }
public IEnumerable<TimesheetListModel> List { get; set; }
public TimesheetModel() { List = new List<TimesheetListModel>(); }
}
并且
public class TimesheetListModel
{
public DateTime Date { get; set; }
public bool? InProgress { get; set; }
public string Note { get; set; }
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public string Task { get; set; }
public decimal? TimeWorked { get; set; }
public int? Type { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
public int? WorkItemId { get; set; }
}
我的任务是通过UserId过滤此模型
{
"TaskDate": "2015-01-04T00:00:00",
"List": [
{
"WorkItemId":24,
"ProjectId":3,
"ProjectName":"Hello world",
"UserId":12,
"UserName":"Anatoliy Svetliakov",
"Date":"2015-01-04T22:00:00",
"Task":"#34 : New task test",
"TimeWorked":2,
"Note":null,
"InProgress":false
}
]
}
答案 0 :(得分:4)
你在两个lambda表达式中使用x作为变量(obj.Where,即父范围&amp; list.Where,这是当前范围),试试这个:
public IEnumerable<TimesheetModel> FilterByUserId(IEnumerable<TimesheetModel> obj, int FilterUserId)
{
var query = (from list in obj.Where(z=>z.List.Any(u=>u.UserId==FilterUserId))
select new TimesheetModel
{
TaskDate = list.TaskDate,
List = list.List.Where(o=> o.UserId.Equals(FilterUserId)).FirstOrDefault()
}).ToList();
return query;
}
答案 1 :(得分:2)
错误信息是自解释的,你需要不同的变量: -
from list in obj.Where(x => x.List.Where(z => z.UserId.Equals(FilterUserId)))
此外,在比较Any
时,您的查询应该使用Where
而不是UserId
: -
var query = (from list in obj.Where(x => x.List.Any(z => z.UserId.Equals(FilterUserId)))
select new TimesheetModel
{
TaskDate = list.TaskDate,
List = list.List
}).ToList();
答案 2 :(得分:1)
您需要一个不同于x的变量,如下所示:
var query = (from list in obj.Where(x => x.List.Where(y => y.UserId.Equals(FilterUserId)))
select new TimesheetModel
{
TaskDate = list.TaskDate,
List = list.List
}).ToList();