【问题标题】:Select data from anonymous collection从匿名集合中选择数据
【发布时间】:2015-04-29 10:56:13
【问题描述】:

如何从第二个查询中获得第一个查询的输出。

查询 1:

var students = context.Students.Select(o => new
        {
            id = o.StdId,
            name = o.Name
        });

查询 2:

var students = context.Database.SqlQuery<object/??>("SELECT  StdId id, Name name FROM Students");

【问题讨论】:

标签: c# linq


【解决方案1】:

您不能将context.Database.SqlQuery 与匿名类型一起使用。你需要定义你的 Student 类(带有 Id、Name)并使用它。

【讨论】:

    【解决方案2】:

    见下方代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    using System.Data;
    
    namespace ConsoleApplication21
    {
        class Program
        {
            static void Main(string[] args)
            {
                string connStr = "Enter your connection string here";
                string SQL = "SELECT  StdId id, Name name FROM Students";
    
                SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
    
                DataTable dt = new DataTable();
                adapter.Fill(dt);
    
                var student = dt.AsEnumerable()
                    .Select(x => new { id = x.Field<int>("id"), name = x.Field<string>("name") }).ToList();
    
            }
        }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2023-04-09
      • 2010-10-14
      • 1970-01-01
      • 2017-03-23
      相关资源
      最近更新 更多