我想創建一個LINQ表達式選擇器來容納另一個IQueryable作爲參數。該dot.net小提琴是here表達式<Func <TSource,TResult >>選擇器與參數
我試圖代碼的CustomSelector接受的IQueryable parameter
並將其應用到視情況選擇。
另外,我想包含在調用CustomSelector將每行的值應用於IQueryable參數。
這樣我就不必編寫2個自定義選擇器。
替代方案是GetMyData2函數。
測試代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EntityDto
{
public int Id { get; set; }
public string Name { get; set; }
public int Count { get; set; }
}
public class TestController
{
public List<Entity> entityList { get; set; }
public List<EntityDto> GetMyData(string condition)
{
List<Entity> sourceEntityList = new List<Entity>();
List<EntityDto> returnEntityList = new List<EntityDto>();
switch(condition)
{
case "A":
returnEntityList = sourceEntityList.Where(x=>x.Name == "A").Select(y=>CustomSelector(sourceEntityList.Where(z=>z.Name=x.Name)));
return returnEntityList;
break;
case "B":
default:
returnEntityList = sourceEntityList.Where(x=>x.Name == "B").Select(y=>CustomSelector(sourceEntityList.Where(z=>z.Name != x.Name)));
return returnEntityList;
break;
}
}
public List<EntityDto> GetMyData2(string condition)
{
List<Entity> sourceEntityList = new List<Entity>();
List<EntityDto> returnEntityList = new List<EntityDto>();
switch(condition)
{
case "A":
returnEntityList = sourceEntityList.Where(x=>x.Name == "A").Select(ent=>
new EntityDto()
{
Id = ent.Id
,
Name = ent.Name
,
Count = sourceEntityList.Count(z=>z.Name== ent.Name)
}
).ToList();
return returnEntityList;
break;
case "B":
default:
returnEntityList = sourceEntityList.Where(x=>x.Name == "B").Select(ent=>
new EntityDto()
{
Id = ent.Id
,
Name = ent.Name
,
Count = sourceEntityList.Count(z=>z.Name != ent.Name)
}
).ToList();
return returnEntityList;
break;
}
}
protected Func<Entity, EntityDto> CustomSelector(IQueryable<Entity> paramQuery)
{
return ent => new EntityDto()
{
Id = ent.Id
,
Name = ent.Name
,
Count = paramQuery.Count()
};
}
}
而你的問題是... –
如何創建一個LINQ表達式選擇器來容納另一個IQueryable作爲參數? –