Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 仅显示字符串数组中的列_C#_Entity Framework_Linq - Fatal编程技术网

C# 仅显示字符串数组中的列

C# 仅显示字符串数组中的列,c#,entity-framework,linq,C#,Entity Framework,Linq,我的实体中有一个表,有370列!此外,我还有一个在运行前未知的字符串数组(来自一个网站) e、 g: 我如何向实体发出linq,只给出给定列的结果 我搜索了几个小时,但直到现在都没有成功-有什么建议吗?这不是你可以用Linq做的事情。您需要能够在代码中声明列 更好的方法是使用数组中的列名在Sql中创建查询,并使用类似的方法将结果映射到对象。您可以在委托中实例化ExpandooObject,并使用反射来获取传入数组中指定的列 以下是: List<IDictionary<String,

我的实体中有一个表,有370列!此外,我还有一个在运行前未知的字符串数组(来自一个网站)

e、 g:

我如何向实体发出linq,只给出给定列的结果


我搜索了几个小时,但直到现在都没有成功-有什么建议吗?

这不是你可以用Linq做的事情。您需要能够在代码中声明列


更好的方法是使用数组中的列名在Sql中创建查询,并使用类似的方法将结果映射到对象。

您可以在委托中实例化ExpandooObject,并使用反射来获取传入数组中指定的列

以下是:

List<IDictionary<String, Object>> List = Context.Row_Type.Select(delegate(Row_Type Row) {

      IDictionary<String, Object> Out = new ExpandoObject() as IDictionary<String, Object>;

      PropertyInfo[] PIs = Row.GetType().GetProperties();

      foreach(PropertyInfo PI in PIs) {
        if(PI.GetIndexParameters().Length == 0) {
          Out.Add(PI.Name, PI.GetValue(Row));
        }
      }

      return Out;

    }).ToList();

我猜您并不是真的想返回一个列名未知的类。列名称和值的字典对您有用吗?您的查询仍然必须检索所有列,但只能返回您关心的列

string [] columns = {"column1", "column2", "column3"}

var entity = GetEntity();
var dictionary = columns.ToDictionary(c => c, c => entity.GetType().GetProperty(c).GetValue(entity));
或者,如果你有收藏

var entities = GetEntities();
var results = entities
    .Select(e => columns.ToDictionary(c => c, c => e.GetType().GetProperty(c).GetValue(e)));

事实并非如此。你可以使用reflection,我该如何使用reflection?你有例子吗?即使它可以与reflection一起使用,这也是一个典型的用例,不适合LINQ to Entities。当您拥有C#类(实体)并且希望基于这些类进行查询时,LINQ to Entities是理想的选择。在这里,老式的
DataReader
s听起来更合适。哇-真的很酷,解决了我的问题,这正是我需要的!谢谢你的大拇指
string [] columns = {"column1", "column2", "column3"}

var entity = GetEntity();
var dictionary = columns.ToDictionary(c => c, c => entity.GetType().GetProperty(c).GetValue(entity));
var entities = GetEntities();
var results = entities
    .Select(e => columns.ToDictionary(c => c, c => e.GetType().GetProperty(c).GetValue(e)));