Selecting a row from a particular column datatable without LINQ - c#

My DataTable has the columns - Id, Name, Address. I need to select the column Address only WHERE ID = 7. How do I do this ? No LINQ please.
I was thinking of this -
DataView view = new DataView(MyDataTable);
DataTable distinctValues = view.ToTable(true, "ColumnA");
Now you can select.
DataRow[] myRows = distinctValues.Select();
//Get the desired answer by iterating myRows.
Is there a simpler way ?
thanks.

Well if you don't want to use LINQ, you can use a simple foreach loop:
DataTable distinctValues = view.ToTable(true, "ColumnA");
var myRows = new List<DataRow>();
foreach(DataRow row in distinctValues.Rows)
{
if(row["Id"].ToString() == "7") myRows.Add(row);
}

Related

How To select Specific Column From DataTable in C#?

I have a dataTable with 4 columns ,
I want to select one column without foreach or any other expensive loop and my result must be a new data table with one column ,How can I do this;
DataTable leaveTypesPerPersonnel = LeaveGroup.GetLeaveTypesPerPersonnels(dtPersonnel.row);
leaveTypesPerPersonnel has this columns :
[ID,Guid,LeaveTypeID,Code]
I want Filter leaveTypesPerPersonnel wihtout foreach and get new datatable with just Column [ID]
NOTE: Output must be a Datatable With one column.
leaveTypesPerPersonnel.Columns.Remove("Guid");
leaveTypesPerPersonnel.Columns.Remove("LeaveTypeID");
leaveTypesPerPersonnel.Columns.Remove("Code");
or
DataTable dt= new DataView(leaveTypesPerPersonnel).ToTable(false,"ID");
You should be able to run a quick LINQ statement against the data table.
var results = (from item in leaveTypesPerPersonnel
select item.ID);
This will give you an IEnumerable if I remember correctly. It's not a DataTable, but might provide a solution to your problem as well.
Here is a try on how to search and convert the result to DataTable
var dataTable = leaveTypesPerPersonnel.Rows.Cast<DataRow>().ToList().Where(x=> x["ID"] == 21).CopyToDataTable().DefaultView.ToTable(false, "ID");
Or
var dataTable = leaveTypesPerPersonnel.Select("ID = 21").CopyToDataTable().DefaultView.ToTable(false, "ID");
Or
var dataTable = leaveTypesPerPersonnel.Rows.Cast<DataRow>().ToList().CopyToDataTable().DefaultView.ToTable(false, "ID");

Searching for a string a column in datatable

I am getting a datatable object of a certain type from strongly typed dataset, now I want to find out if one of the column "Title" has certain string in it.
I am trying this, is there any better way ?
FruitDataAccess fda = new FruitDataAccess();
FruitDataTable fdt = cda.GetFriuts(fruitCrateID);
DataTable dt = fdt.CopyToDataTable();
var row = dt.Rows.Cast<DataRow>().Any(r => r.ItemArray.Any(c => c.ToString().Contains("whatever")));
Use LINQ TO DataSet/DataTable like:
var search = dt.AsEnumerable()
.FirstOrDefault(r=> r.Field<string>("Title") == "your string");
if(search != null)
{
//found
}
You can also find rows with your condition like:
DataRow[] foundRows;
foundRows = dt.Select("Title Like '%your string%'"); //similar to Contains
See: How to: Locate a Specific Row in a DataTable

Sort a string column by datetime in a DataTable

I am trying to sort a DataTable on a string column by DateTime.
For various reasons, the column must be left as a string data type. I know I can copy the data out into another table, convert that column to a DateTime column, sort on that and copy it back but I'm wondering if there's a neater way.
I've tried the basics of DefaultView and LINQ to no prevail.
Try Add while create DataTable
table.Columns.Add("dateValue", typeof(DateTime?));
var orderedRows = from row in dt.AsEnumerable()
orderby row.Field<DateTime>("Date")
select row;
DataTable tblOrdered = orderedRows.CopyToDataTable();
(Or)
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.Parse(row.Field<string>("Date"), CultureInfo.InvariantCulture)
orderby date
select row;
Stumbled upon a method right after I posted.
EnumerableRowCollection<DataRow> query = from row in dataTable.AsEnumerable()
orderby DateTime.Parse(row.Field<string>(propertyName)) ascending
select row;
dataTable = query.AsDataView().ToTable();
You can sort dates as a string if you use the format YYYYMMDD
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
rows.Sort((r1,r2)=>DateTime.Parse((string)r1["columnname"]).CompareTo(DateTime.Parse((string)r2["columnname"])));
var clone = table.Clone();
rows.ForEach(r => clone.Rows.Add(r.ItemArray));
return clone;

Filtering a empty string in DataTable

How do filter a empty String in DataTable?
I need to filter a column (say Customer Name where the name is string.Empty)
I tried this but i cant get into right way..
I need to filter the DataView through DataView.RowFilter.. so how to give filter string for string.Empty..
Any idea on this?
To filter a dataTable-
dt.Select("customer_name = ''");
To Filter datatview-
dv.RowFilter = "customer_name = ''";
Use Select method:
DataRow[] foundRows = dt.Select("MyColumn = ''");
You can use Select method for DataTable:
//selects all customers which name is empty
var rows = dtData.Select("CustomerName = ''");
See the code below, might be a help. I am answering as the question has a tag RowFilters
private void GetRowsByFilter()
{
DataTable table = DataSet1.Tables["YourTable"];
// Presuming the DataTable has a column named Date.
string expression = "Column_name = ''";
// Sort descending by column named CompanyName.
string sortOrder = "ColumnName DESC";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression, sortOrder);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
}
Try below code:
DataTable dt=new DataTable();
DataRow dr;
dr=dt.NewRow();
if(dr["CustomerName"]==null)
{
put some code here.........
}
i Hope This code will help 4 u

Linq on DataTable: select specific column into datatable, not whole table

I'm running a LINQ query on a datatable in c#.
I want to select specific columns rather than the whole row and enter the result into a datatable. How can i do that??
My Code:
public DataTable getConversions(string c_to, string p_to)
{
var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == c_to &&
r.Field<string>("p_to") == p_to
select r;
DataTable conversions = query.CopyToDataTable();
If you already know beforehand how many columns your new DataTable would have, you can do something like this:
DataTable matrix = ... // get matrix values from db
DataTable newDataTable = new DataTable();
newDataTable.Columns.Add("c_to", typeof(string));
newDataTable.Columns.Add("p_to", typeof(string));
var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == "foo" &&
r.Field<string>("p_to") == "bar"
let objectArray = new object[]
{
r.Field<string>("c_to"), r.Field<string>("p_to")
}
select objectArray;
foreach (var array in query)
{
newDataTable.Rows.Add(array);
}
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
Here I get only three specific columns from mainDataTable and use the filter
DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");
LINQ is very effective and easy to use on Lists rather than DataTable. I can see the above answers have a loop(for, foreach), which I will not prefer.
So the best thing to select a perticular column from a DataTable is just use a DataView to filter the column and use it as you want.
Find it here how to do this.
DataView dtView = new DataView(dtYourDataTable);
DataTable dtTableWithOneColumn= dtView .ToTable(true, "ColumnA");
Now the DataTable dtTableWithOneColumn contains only one column(ColumnA).
Your select statement is returning a sequence of anonymous type , not a sequence of DataRows. CopyToDataTable() is only available on IEnumerable<T> where T is or derives from DataRow. You can select r the row object to call CopyToDataTable on it.
var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == c_to &&
r.Field<string>("p_to") == p_to
select r;
DataTable conversions = query.CopyToDataTable();
You can also implement CopyToDataTable Where the Generic Type T Is Not a DataRow.

Categories