Domanda

Sto cercando di eseguire una query LINQ su un oggetto DataTable e stranamente mi sto trovando che l'esecuzione di tali query su tabelle di dati non è semplice.Per esempio:

var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;

Questo non è consentito.Come posso ottenere qualcosa di simile a questo lavoro?

Sono stupito che le query LINQ non sono ammessi su Datatable!

È stato utile?

Soluzione

Non è possibile eseguire query sul DataTable's Righe la raccolta, dal momento che DataRowCollection non implementare IEnumerable<T>.È necessario utilizzare il AsEnumerable() estensione per DataTable.In questo modo:

var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;

E come Keith dice, è necessario aggiungere un riferimento a Sistema.Dati.DataSetExtensions

AsEnumerable() restituisce IEnumerable<DataRow>.Se avete bisogno di convertire IEnumerable<DataRow> per un DataTable, utilizzare il CopyToDataTable() estensione.

Qui di seguito è una query con Espressione Lambda,

var result = myDataTable
    .AsEnumerable()
    .Where(myRow => myRow.Field<int>("RowNo") == 1);

Altri suggerimenti

var results = from DataRow myRow in myDataTable.Rows
    where (int)myRow["RowNo"] == 1
    select myRow

Non è che siano stati deliberatamente non ammessi su Datatable, è solo che Datatable pre-data la IQueryable e IEnumerable generico costrutti in cui le query Linq può essere eseguita.

Entrambe le interfacce richiedono un qualche tipo di tipo di validazione della sicurezza.Datatable non sono fortemente tipizzati.Questo è lo stesso motivo per cui la gente non può query a fronte di un ArrayList, per esempio.

Per Linq to di lavoro è necessario mappare i risultati contro type-safe oggetti e query che invece.

Come @ch00k ha detto:

using System.Data; //needed for the extension methods to work

...

var results = 
    from myRow in myDataTable.Rows 
    where myRow.Field<int>("RowNo") == 1 
    select myRow; //select the thing you want, not the collection

È inoltre necessario aggiungere un riferimento al progetto System.Data.DataSetExtensions

var query = from p in dt.AsEnumerable()
                    where p.Field<string>("code") == this.txtCat.Text
                    select new
                    {
                        name = p.Field<string>("name"),
                        age= p.Field<int>("age")                         
                    };

Mi rendo conto che questo è stato risposto un paio di volte, ma solo per offrire un altro approccio, mi piace usare il .Cast<T>() metodo, mi aiuta a mantenere la sanità mentale nel vedere il tipo esplicito definito, e in fondo penso .AsEnumerable() chiama comunque:

var results = from myRow in myDataTable.Rows.Cast<DataRow>()
                  where myRow.Field<int>("RowNo") == 1 select myRow;

o

var results = myDataTable.Rows.Cast<DataRow>()
                  .FirstOrDefault(x => x.Field<int>("RowNo") == 1);
//Create DataTable 
DataTable dt= new DataTable();
dt.Columns.AddRange(New DataColumn[]
{
   new DataColumn("ID",typeOf(System.Int32)),
   new DataColumn("Name",typeOf(System.String))

});

//Fill with data

dt.Rows.Add(new Object[]{1,"Test1"});
dt.Rows.Add(new Object[]{2,"Test2"});

//Now  Query DataTable with linq
//To work with linq it should required our source implement IEnumerable interface.
//But DataTable not Implement IEnumerable interface
//So we call DataTable Extension method  i.e AsEnumerable() this will return EnumerableRowCollection<DataRow>


// Now Query DataTable to find Row whoes ID=1

DataRow drow = dt.AsEnumerable().Where(p=>p.Field<Int32>(0)==1).FirstOrDefault();
 // 

Utilizzando LINQ to manipolare i dati nel DataSet/DataTable

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

Provate questa semplice linea di query:

var result=myDataTable.AsEnumerable().Where(myRow => myRow.Field<int>("RowNo") == 1);

È possibile utilizzare LINQ to objects sulle Righe di raccolta, in questo modo:

var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;

Prova questo

var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ; 

Questo è un modo semplice che funziona per me e utilizza espressioni lambda:

var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1)

Poi, se volete un valore particolare:

if(results != null) 
    var foo = results["ColName"].ToString()

Molto probabilmente, le classi per il DataSet, DataTable e DataRow sono già definiti nella soluzione.Se questo è il caso, non è necessario il DataSetExtensions di riferimento.

Ex.Classe DataSet nome-> CustomSet, DataRow nome della classe-> CustomTableRow (con colonne definite:RowNo, ...)

var result = from myRow in myDataTable.Rows.OfType<CustomSet.CustomTableRow>()
             where myRow.RowNo == 1
             select myRow;

O (come preferisco)

var result = myDataTable.Rows.OfType<CustomSet.CustomTableRow>().Where(myRow => myRow.RowNo);
var results = from myRow in myDataTable
where results.Field<Int32>("RowNo") == 1
select results;

Nella mia applicazione ho scoperto che l'utilizzo di LINQ to Dataset con il AsEnumerable() estensione per DataTable come suggerito nella risposta è stato estremamente lento.Se siete interessati all'ottimizzazione per la velocità, l'uso di James Newtonking s Json.Net biblioteca (http://james.newtonking.com/json/help/index.html)

// Serialize the DataTable to a json string
string serializedTable = JsonConvert.SerializeObject(myDataTable);    
Jarray dataRows = Jarray.Parse(serializedTable);

// Run the LINQ query
List<JToken> results = (from row in dataRows
                    where (int) row["ans_key"] == 42
                    select row).ToList();

// If you need the results to be in a DataTable
string jsonResults = JsonConvert.SerializeObject(results);
DataTable resultsTable = JsonConvert.DeserializeObject<DataTable>(jsonResults);

Esempio su come ottenere questo qui di seguito riportato:

DataSet dataSet = new DataSet(); //Create a dataset
dataSet = _DataEntryDataLayer.ReadResults(); //Call to the dataLayer to return the data

//LINQ query on a DataTable
var dataList = dataSet.Tables["DataTable"]
              .AsEnumerable()
              .Select(i => new
              {
                 ID = i["ID"],
                 Name = i["Name"]
               }).ToList();

Per VB.NET Il codice sarà simile a questa:

Dim results = From myRow In myDataTable  
Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow
IEnumerable<string> result = from myRow in dataTableResult.AsEnumerable()
                             select myRow["server"].ToString() ;

Prova questo...

SqlCommand cmd = new SqlCommand( "Select * from Employee",con);
SqlDataReader dr = cmd.ExecuteReader( );
DataTable dt = new DataTable( "Employee" );
dt.Load( dr );
var Data = dt.AsEnumerable( );
var names = from emp in Data select emp.Field<String>( dt.Columns[1] );
foreach( var name in names )
{
    Console.WriteLine( name );
}

Si può ottenere un lavoro elegante via linq come questo:

from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()
where prod.Field<decimal>("UnitPrice") > 62.500M
select prod

O come dinamico, linq questo (AsDynamic è chiamato direttamente sul DataSet):

TenMostExpensiveProducts().AsDynamic().Where (x => x.UnitPrice > 62.500M)

Io preferisco l'ultimo approccio, mentre è è il più flessibile.P. S.:Non dimenticare di collegare System.Data.DataSetExtensions.dll riferimento

si può provare questo, ma è necessario assicurarsi che il tipo di valori per ciascuna Colonna

List<MyClass> result = myDataTable.AsEnumerable().Select(x=> new MyClass(){
     Property1 = (string)x.Field<string>("ColumnName1"),
     Property2 = (int)x.Field<int>("ColumnName2"),
     Property3 = (bool)x.Field<bool>("ColumnName3"),    
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top