c# - linq 选择集合列动态

标签 c# linq linq-to-sql linq-query-syntax

例如,我想在 linq 命令中通过动态选择 Col1 或 Col2

var temp1= "Col1";

谢谢你的回答

我试试

((ICollection<SanadItem>)x.GetType().GetProperty(temp1).GetType()).Select(g =>...

但出现错误 LINQ to Entities 无法识别方法 'System.Type GetType()' 方法

public class class1 {
 public int Id {get; set;}
 public string Name {get; set;}
 public string Code {get; set;}
 public ICollection<Class2> Col1 {get; set;}
 public ICollection<Class2> Col2 {get; set;}
}

public class class2 {
 public int Id {get; set;}
 public int Id2 {get; set;}
 public int Bed {get; set;}
 public int Bes {get; set;}
}
...
..
.

public class mycontext:dbcontext{
  public DbSet<Class1> class1 { get; set; }
  public DbSet<Class2> class2 { get; set; }
}

var db = new mycontext()
var qbase = db.class1;
        var qbase2 = qbase.Select(x => new
        {
            Id = x.Id,
            Code = x.Code,
            Name = x.Name,
           //--> I want select x.Col1 or x.Col2 by Dynamic but I cannot use library Linq.Dynamic
            items =  x.Col1.Where(xx => xx.Id2 == x.Id).GroupBy(b=>b.Id2).Select(y =>
                new
                { 
                    Bed = y.Sum(c=>c.Bed),
                    Bes = y.Sum(c => c.Bes),
                })                  
        }); 

最佳答案

这样试试

var qbase2 = qbase.Select(x => new
        {
            Id = x.Id,
            Code = x.Code,
            Name = x.Name,
            DynamicCol = (int)s.GetType().GetProperty("Col1").GetValue(x, null) ,
            //Remember to cast the dynamic column according to its datatype
            items =  x.Col1.Where(xx => xx.Id2 == x.Id).GroupBy(b=>b.Id2).Select(y =>
                new
                { 
                    Bed = y.Sum(c=>c.Bed),
                    Bes = y.Sum(c => c.Bes),
                })                  
        }); 

关于c# - linq 选择集合列动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23286200/

相关文章:

c# - SQL Server 参数化 SQL 查询 - 我还需要转义引号吗?

c# - 如何为 Entity Framework 编写共享方法

c# - 如何确保序列具有一定长度?

LINQ FirstOrDefault问题

c# - InstancePerRequest DbContext ASP.NET MVC

c# - ChangeTracker.Entries() CurrentValue 等于 EF7 中的 OriginalValue

c# - 在 Visual Studio 或 SQL Server Management Studio 中连接到 Azure SQL 数据库需要执行哪些步骤?

c# - 如何按自定义顺序对列表进行排序

linq-to-sql - 跨多个数据库构建数据层的最佳方法是什么?

c# - LINQ2SQL 获取随机记录