How to convert a dataset to a list in c# - c#

Is there a way to convert a dataset to a list, there's a lot of example with
datatable but with dataset I have not found.

A Dataset is a collection of DataTables. All you need to do is iterate through each table of the DataSet. This data will typically be different structures, though, so you would want a List for each table.
foreach (var dt in myDataSet.Tables)
{
var list = dt.AsEnumerable()
.Select(dr=> new
{
Name = dr.Field<string>("Name"),
Valuw = dr.Field<string>("Value")
}).ToList();
// do something with your list
}

i think you should use
List<string> list = ds.Tables[0].AsEnumerable().Select(r => r.Field<string>("Name")).ToList();

Related

LINQ result in DataRow

I have an XML for which I have used LINQ to XML. As I wanted to capture some of the element/ attribute data, I have taken them in a string array. Later I have used a foreach loop to insert these values from string array to a DataRow; as my final goal is to get a DataTable out of it.
Following is my code
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("col_1");
dt.Columns.Add("col_2");
dt.Columns.Add("col_3");
string[] arr = new string[3];
var myData = from n in doc.Descendants("product")
select new string[]{
arr[0] = n.Attribute("name").Value,
arr[1] = n.Attribute("prodid").Value,
arr[2] = n.Attribute("price").Value
};
foreach (var item in myData)
{
dt.Rows.Add(item[0],item[1],item[2]);
}
Is is possible to combine these and directly get an output as DataTable from LINQ query instead of using foreach?
Instead of select new string[] can I use something like select new DataTable or instance of DataTable?
I understand that my Table structure should be fixed.
Update
Thanks #CodingDawg & #Rahul Singh, I would now like to know the best approach between these two.
I will check for my sample data to compare the same.
But from your experience which one is better considering large data (10000 elements => 10000 rows)?
There is way to load entire XML into DataSet but I guess you need some specific values and also need to do some custom filtering or stuffs thus you are using Linq-to-XML, you can project the datatable directly without using foreach loop like this:-
DataTable myData = doc.Descendants("product")
.Select(x =>
{
var row = dt.NewRow();
row.SetField<string>("col_1", (string)x.Attribute("name"));
row.SetField<string>("col_2", (string)x.Attribute("prodid"));
row.SetField<string>("col_1", (string)x.Attribute("price"));
return row;
}).CopyToDataTable();
myData will hold the resultant dataTable.
Use the Linq .ToList().ForEach() functions
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("col_1");
dt.Columns.Add("col_2");
dt.Columns.Add("col_3");
doc.Descendants("product")
.ToList()
.ForEach(
n => dt.Rows.Add(n.Attribute("name").Value,
n.Attribute("prodid").Value,
n.Attribute("price").Value));

Linq Query for querying a list of DataSet

I have a list of DataSet.
for example:
List<DataSet> list = new List<DataSet>();
For my task, the number of DataSet in the list and the number of DataTable in each DataSet will be known at the run time.
Now I want to get those tables from the DataSets that contains a certain string in their names, for instance say 'Group1'.
I am trying with the following code:
var ds= from set in list from table in set
where li.Where(e=>e.Tables.Contains("Group")) select table;
But i am getting the error as 'An expression of type System.Data.DataSet is not allowed in a subsequent from clause in a query expression with source typeList'.
Please help me with the correct approach.
I've tried to replicate your data structure by creating another class. Hope this helps.
namespace TestCode
{
class Program
{
static void Main(string[] args)
{
var list = new List<TC> {new TC(2), new TC(2), new TC(3), new TC(4), new TC(5), new TC(2)};
var dt = list.Where( // Contains 3 elements
x => x.X == 2
);
//var ds = from set in list
// from table in set
// where li.Where(e => e.Tables.Contains("Group"))
// select table;
}
}
internal class TC
{
public int X { get; set; }
internal TC(int val)
{
X = val;
}
}
}
You original query is close. It just needs to be fleshed out a bit. First off it helps to declare the type in the from statement. Also specify you want the table collection from the set. The where clause should just need to examine the TableName property of the tables:
List<DataSet> list = new List<DataSet>();
var ds = from DataSet set in list
from DataTable table in set.Tables
where table.TableName.Contains("Group")
select table;
This gets the tables with the contained name:
var tables = list.SelectMany(x => x.Tables.Cast<DataTable>())
.Where(x => x.TableName.Contains("Group"));

How can I put the rows on an specific column in a int[]? Visual Studio

So, I have a table named Muestras(I created it with Access). It has only one column called "Muestras" also. It only has random numbers (33,83,42, etc), a total of 30.
I want to put all of these numbers inside an int[]. How can I do it?
OleDbConnection conexionMuestra = new
OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\Users\Roberto\Documents\Muestra_pv.accdb");
OleDbDataAdapter adaptador = new OleDbDataAdapter("Select * from Muestra", conexionMuestra);
DataTable tablaM = new DataTable();
adaptador.Fill(tablaM);
So you have a DataTable with one column and you need an int[]?
One way:
int[] result = tablaM.AsEnumerable()
.Select(r => r.Field<int>(0)) // or via column-name r.Field<int>("Muestras")
.ToArray();
if it's actually a string column you need to parse it first:
int[] result = tablaM.AsEnumerable()
.Select(r => int.Parse(r.Field<string>(0)))
.ToArray();
I would use an arrayList if the table is going to continue to grow with a foreach loop or a while loop.
ArrayList al = new ArrayList();
while(tablaM.hasrows)
{
al.add("data");
}
my syntax is probably off as I haven't used c# in a while but that should give you an idea

dynamic datatable sorting in ascending or descending

I have created dynamic table
DataTable date = new DataTable();
date.Columns.Add("date1");
and made fill the column name "date1" with date as
date1(Column name)
05-07-2013
10-07-2013
09-07-2013
02-07-2013
and made fill my dynamic table
Now i want this dynamic table data to be sort as ascending or descending order
For eg:
date1(Column name)
02-07-2013
05-07-2013
09-07-2013
10-07-2013
This cannot be done with the original data table. However you can create a new, sorted one:
DataView view = date.DefaultView;
view.Sort = "date1 ASC";
DataTable sortedDate = view.ToTable();
You can use DataTable.Select(filterExpression, sortExpression) method.
Gets an array of all DataRow objects that match the filter criteria,
in the specified sort order.
date.Select("", "YourColumn ASC");
or
date.Select("", "YourColumn DESC");
As an alternative, you can use DataView like;
DataView view = date.DefaultView;
view.Sort = "YourColumn ASC";
DataTable dt = view.ToTable();
Thought I would give in my two cents here. Instead of using a sorting algorithm which takes time and computational performance, why not instead reverse the way in which you are adding data to your data object.
This won't work for everyone's scenario - but for my own it worked out perfectly.
I had a database which listed items in an ascending order, but or ease of use I needed to reverse the way in which people could see the data (DESC) so that the newest input shows at the top, rather then the bottom of the list.
So, I just changed my for loop so instead of working from 0 -> upwards, it started from the length of the datatable (-1 to stop an overflow) and then stops when it is >= to 0;
private Dictionary<string, string> GetComboData(string table, int column, bool id, int idField = 0)
{
SqlClass sql = new SqlClass(database);
Dictionary<string, string> comboBoxData = new Dictionary<string, string>();
if (sql.connectedToServer)
{
sql.SelectResults(SQLCommands.Commands.SelectAll(table));
for (int i = sql.table.Rows.Count-1; i >= 0; i--)
{
string tool = sql.table.Rows[i].ItemArray.Select(x => x.ToString()).ToArray()[column];
string ID = sql.table.Rows[i].ItemArray.Select(x => x.ToString()).ToArray()[idField];
comboBoxData.Add(ID, tool);
}
}
return comboBoxData;
}
using OrderByDescending()
#foreach (var rca in Model.OrderByDescending(x=>x.Id))
{
<tr class="heading">
<td>#rca.PBINo</td>
<td>#rca.Title</td>
<td>#rca.Introduction</td>
<td>#rca.CustomerImpact</td>
<td>#rca.RootCauseAnalysis</td>
</tr>
}

Ensure a datatable is ordered by a value

I have a complex algorithm which I am not going to explain here. The code pasted below is doing some processing for each row, but I need to ensure that the table is ordered by a field different than the Primary Key.
I need to do this in this code, not in SQL, or in stored procedures; it needs to be done in .net just before the foreach.
NO LINQ IS ALLOWED, ITS .NET 2.0
THX
Your help is appreciated.
List<int> distinctREFMDossierIds = GetREFMDossierIdsFromBookings();
foreach (int refmDossierId in distinctREFMDossierIds)
{
bool errorsFoundInDetails = false;
bool errorsFoundInHeaders = false;
wingsBookingInterfaceIdswithErrors.Clear();
dicRows.Clear();
sbWingsBookingInterfaceIds= new StringBuilder();
YBooking booking = new YBooking();
foreach (UC090_WingsIntegrationDataSet.WingsBookingInterfaceRow row in _uc090_WingsIntegrationDataSet.WingsBookingInterface.Rows)
{
//code
}
You can use LINQ:
foreach(var row in _uc090_WingsIntegrationDataSet.WingsBookingInterface
.OrderBy(r => r. Something))
You can sort a DataTable like this:
DataTable dt = new DataTable();
dt.DefaultView.Sort = <Sort expression>;
dt = dt.DefaultView.ToTable();
WingsBookingInterface.Rows.OrderBy(item => item.columnName);
You can sort a collection ( for example a List<> ) with the OrderBy extension method.

Categories

Resources