How to convert a IEnumerable<DataColumn> into a Datatable? - linq

I got this:
var dsetValueFields = rds.Result.Columns.Cast<DataColumn>().Where(c=>c.DataType==typeof(Decimal));
And need to convert into a DataTable. Tried this:
DataTable dt = new DataTable();
dt.Columns.AddRange(dsetValueFields.ToArray());
But get error, "Column is part of another table."
Thanks!

You'll need to create copies of the columns in your enumerable. Like DataRows, DataColumns can only be attached to one table.
dt.Columns.AddRange(dsetValueFields
.Select(c => new DataColumn(c.Name, c.DataType))
.ToArray());

Related

slickgrid - grid.getDataItem(0), dataView.getItem(0) and .dataView.getItemByIdx(0) returning reference

I'm trying to duplicate a row, but change like one column.
So I do something like this:
var item = myGrid.grid.getDataItem(rowIndex);
item.id=123;
myGrid.dataView.addItem(item);
My issue is that if I am duplicating the row at index 0, when I do:
item.id = 123;
It actually makes id of the row at index 0 as 123 as well as the new line.
Is there a way to get the data and not get the actual reference to the row?
Thanks!
In this case, I would use the jQuery $.extend method to create a new object:
var newItem = {};
$.extend(newItem, item);
newItem.id=123;
myGrid.dataView.addItem(newItem);

Bind Objects To DataGridview and Reorder Column

I want to bind the object list to dataGridView.
Now i want the desired column to be the way i definde them. i.e., I want the objects to be order the way i want.
Like
var dataSource = linkItemListCommon.Select(x => new DataToBind { Select = x.Default, FileName = x.Text, CurrentDate = x.Date+" "+x.Time , PreviousDate = string.Empty, Size = x.Size }).ToList();
var filenamesList = new BindingList<DataToBind>(dataSource);
dgvDownLoadMaster.DataSource = filenamesList;
I want the datagrid columns to be in the order that i define.
Like here i expect them to be in order given below:
Select FileName CurrentDate PreviousDate Size
But the column list is appearing not as per my requirements.
How to Do that.Please help.
Create columns by hand and then you can order them easily. You can add columns trough designer and just set each column DataPropertyName to corresponding field.
Or you can create each column programmatically:
var col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Select ";
col.HeaderText = "Select";
col.Name = "ColSelect";
dgvDownLoadMaster.Columns.Add(col);
you have to do this for each column and do it before databinding.

Update entity columns iterating through col list using LINQ

I can get column list from the table using LINQ like this:
OrderDataContext ctx = new OrderDataContext();
var cols = ctx.Mapping.MappingSource
.GetModel( typeof( OrderDataContext ) )
.GetMetaType( typeof( ProductInformation ) )
.DataMembers;
This gives me the list of columns, so I can do this:
foreach ( var col in cols )
{
// Get the value of this column from another table
GetPositionForThisField( col.Name );
}
So this all works, I can iterate through column list and pull the values for those columns from an another table (since the column names are the keys in that another table), so I don't have to do switch....or lot of if...then...
Now the question:
After I get these values, how do I populate the entity in order to save it back? I would normally go like this:
ProductInformation info = new ProductInformation();
info.SomeField1 = val1;
info.SomeField2 = val2;
ctx.ProductInformation.InsertOnSubmit( info );
ctx.SubmitChanges();
But how to use the same column collection from above to populate the columns while iterating over that, when there is no such thing as:
info["field1"].Value = val1;
Thanks.
Just fetch the object that you want to modofy, set the property and call SubmitChanges. There is no need to create a new object and insert it. The Context tracks your changed properties and generates the update statement accordingly. In your case you may want to set the properties via reflection rather than manually since you are reading them from another table.
You'll need to use reflection. Assuming you can get the PropertyInfo from the metadata:
PropertyInfo property = GetPropertyForThisField(col.Name);
property.SetValue(info, val1, null);

Best way to get individual days from a column, using LINQ

I have the following data in one MSSQL Table column
2011-06-20 11:53:32.000
2011-06-20 11:54:24.000
2011-06-20 11:55:45.000
2011-08-05 10:24:12.000
2011-08-05 10:25:28.000
2011-08-05 10:26:20.000
2011-08-05 10:27:12.000
2011-08-05 10:28:04.000
2011-08-05 10:28:55.000
Using LINQ, I would like to get the following data from the column
2011-06-20
2011-08-05
So I can put into a List<>
What's the best way to do this? I already have the context stuff setup, so I don't need details on that. I just need an idea of the best "query" and logic I can use to get this data. Thanks!
You are looking for all of the Distinct dates in a range of DateTimes, the following will show examples to get what you need, given you already have them in a string or by querying your database:
Example (with list of strings):
var list; //Contains your dates
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
Example (from database table):
List<String> dates = (FROM d in datesTable
SELECT d.date.ToShortDateString()).Distinct().ToList();
Console Example to demonstrate functionality:
List<DateTime> list = new List<DateTime>();
list.Add(DateTime.Parse("2011-06-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:44:32.000"));
list.Add(DateTime.Parse("2011-04-20 11:53:32.000"));
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
foreach (string date in result)
{
Console.WriteLine(date);
}
Console.Read();
var q = from t in mydates select distinct ( t.Date.ToShortDateString());
To select distinct dates into a list try this:
List<String> myDates = (from t in myTable
select t.myDate.ToShortDateString()
).Distinct().ToList()

Can we filter Datatable with LINQ?

Suppose my datatable is filled with data.
After filling data can we again put some condition on datatable with linq to extract data.
Suppose my datatable has 10 employee record.
So can we extract only those employee whose salary is greater than 5000 with linq query.
I know that we can achieve it datatable.select(). How can you achieve this with linq?
You can get a filtered set of rows, yes:
var query = table.AsEnumerable()
.Where(row => row.Field<decimal>("salary") > 5000m);
This uses the AsEnumerable and Field extension methods in DataTableExtensions and DataRowExtensions respectively.
Try this:
var query = (from t0 in dtDataTable.AsEnumerable()
where t0.Field<string>("FieldName") == Filter
select new
{
FieldName = t0.Field<string>("FieldName"),
FieldName2 = t0.Field<string>("FieldName2"),
});

Resources