簡體   English   中英

從匿名集合中選擇數據

[英]Select data from anonymous collection

我如何從第二個查詢中獲取類似第一個查詢的輸出。

查詢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");

您不能使用具有匿名類型的context.Database.SqlQuery 您需要定義學生類(使用ID,名稱)並使用它。

見下面的代碼

 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(); } } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM