gpt4 book ai didi

c# - linq 选择集合列动态

转载 作者:太空宇宙 更新时间:2023-11-03 15:56:37 25 4
gpt4 key购买 nike

例如,我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com