I have been using LinqToExcel Library Lately and i came across this issue.
here is the code
var excel = new ExcelQueryFactory(fileName);
var dataList = (from c in excel.WorksheetRangeNoHeader("A1", "A4", "Test Worksheet")
select c).ToList();
This dataList Collection Will have something like "Cat","Dog" ,"Fish" and "Goat"
Now All i want to do is assign Fish to a variable as an string by doing something like this
string temp=dataList[2];
However when i run the code i get the value of temp as "LinqToExcel.RowNoHeader". Anyone got idea on how to extract the actual value Fish into the variable temp.
Thanks in Advance
Cracked it !
I was referring to the whole row rather than the first cell of each row.
Therefore i needed C[0] in order to get the items.
var excel = new ExcelQueryFactory(fileName);
var dataList = (from c in excel.WorksheetRangeNoHeader("A1", "A4", "Test Worksheet")
select c[0]).ToList();
And the extraction code will be
var temp=Convert.ToString(dataList[2]);
Related
I have a list of object. I want to group this list from two columns and get the last value of this column.
I also want to have the entire copy of the object.
I have write this code:
var FileDaInviare = info.FNAVB00R.ToList();
var FileDaInvNew = from c in FileDaInviare
group c by new
{
c.Progressivo_Gemap,
c.Committente_Gemap,
} into gcs
select new FNAVB00R()
{
};
FileDaInvNew = FileDaInvNew.ToList();
But with this code i have only the first value of the group by(I want the last) and the object is empty. I want copy of the entire object directly please consists of hundred columns.
Thanks to all
You could use Last extension method.
FileDaInvNew = FileDaInviare.GroupBy(g=> new {g.Progressivo_Gemap, g.Committente_Gemap})
.Select(x=>x.Last())
.ToList()
var priv = from emp in re.Users
where emp.Name == struname
select new { emp.privilege };
for the privilege i have manager, officer and applicant
when i press a button on the form i want to show the (priv) in a label or a textbox i have tried it does not work even when i convert it to string like label.Text= priv.ToString() but it still does not show me mananger, officer or applicant i dont know why
can you help me please
thanks in advance
#r.hamd I saw your auto-answer and I think that, although it works, is very confusing: as Binkan said you are creating and object while you need only a property.
I suggest this cleaner version:
Label.Text = re.Users.Single(u=> u.Name == struname).privilege;
Of course you have to try-catch this because if match fails you can't access privilege property.
One final note: properties should start with capital letter, therefore you should rename privilege to Privilege.
thank you all very much for your contribution
i modified the code as the following and it worked properly for me
var priv = (from emp in re.Users
where emp.Name == struname
select emp.privilege );
Label.Text = priv.FirstOrDefault().ToString();
You are returning an anonymous type with select new { emp.privilege }. Maybe you meant select emp or select emp.privilege?
I have 2 datatables named 'dst' and 'dst2'. they are located in the dataset 'urenmat'.
The mayority of the data is in 'dst'. this however contains a column named 'werknemer'. It contains a value which corresponds to a certain row in 'dst2'. This column is named 'nummer'.
What i need is a way to left outer join both datatables where dst.werknemer and dst2.nummer are linked, and a new datatable is created which contains 'dst2.naam' linked to 'dst.werknemer' along with all the other columns from 'dst'.
I have looked everywhere and still can't seem te find the right answer to my question. several sites provide a way using LINQ in this situation. I have tried using LINQ but i am not so skilled at this.
I tried using the 101 LINQ Samples:
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
urenmat = dataset.
dst = a, b, c, d, werknemer.
dst2 = nummer, naam.
I used the following code from '101'.
var query =
from contact in dst.AsEnumerable()
join order in dst2.AsEnumerable()
on contact.Field<string>("werknemer") equals
order.Field<string>("nummer")
select new
{
a = order.Field<string>("a"),
b = order.Field<string>("b"),
c = order.Field<string>("c"),
d = order.Field<string>("d"),
naam = contact.Field<decimal>("naam")};
I however don't know what to change 'contact' and 'order' to and i can't seem to find out how to save it to a datatable again.
I am very sorry if these are stupid questions but i have tried to solve it myself but it appears i'm stupid:P. Thank for the help in advance!
PS. i am using C# to code, the dataset and datatables are typed.
if you want to produce a projected dataset of dst left outer joined to dst2 you can use this LINQ expression (sorry i don't really work in LINQ query syntax so you'll have to use this lambda syntax instead).
var query = dst.AsEnumerable()
.GroupJoin(dst2.AsEnumerable(), x => x.Field<string>("werknemer"), x => x.Field<string>("nummer"), (contact, orders) => new { contact, orders })
.SelectMany(x => x.orders.DefaultIfEmpty(), (x, order) => new
{
a = order.Field<string>("a"),
b = order.Field<string>("b"),
c = order.Field<string>("c"),
d = order.Field<string>("d"),
naam = x.contact.Field<decimal>("naam")
});
because this is a projected dataset you cannot simply save back to the datatable. If saving is desired then you would want to load the affected row, update the desired fields, then save the changes.
// untyped
var row = dst.Rows.Find(keyValue);
// typed
var row = dst.FindBy...(keyValue);
// update the field
row.SetField("a", "some value");
// save only this row's changes
row.AcceptChanges();
// or after all changes to the table have been made, save the table
dst.AcceptChanges();
Normally if you need to perform loading and saving of (projected) data, an ORM (like entity framework, or LINQ-to-SQL) would be the best tool. However, you are using DataTable's in this case and I'm not sure if you can link an ORM to these (though it seems like it would probably be possible).
I am pulling in a Dapper FastExpando object and want to be able to reference the column names dynamically at run time rather than at design/compile time. So I want to be able to do the following:
var testdata = conn.Query("select * from Ride Where RiderNum = 21457");
I want to be able to do the following:
foreach( var row in testdata) {
var Value = row["PropertyA"];
}
I understand that I can do:
var Value = row.PropertyA;
but I can't do that since the name of the property i'm going to need won't be known until runtime.
The answer from this SO Question doesn't work. I still get the same Target Invocation exception. So...
Is there any way to do what I want to do with a Dapper FastExpando?
Sure, it is actually way easier than that:
var sql = "select 1 A, 'two' B";
var row = (IDictionary<string, object>)connection.Query(sql).First();
row["A"].IsEqualTo(1);
row["B"].IsEqualTo("two");
Regarding the portion of the title "or index?" - I needed to access results by index since the column names being returned changed sometimes, so you can use a variation of Sam Saffron's answer like this:
var sql = "select 1, 'two'";
var row = (IDictionary<string, object>)connection.Query(sql).First();
row.Values.ElementAt(0).IsEqualTo(1);
row.Values.ElementAt(1).IsEqualTo("two");
There a simple way to access fields direct below sample
string strConexao = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
conexaoBD = new SqlConnection(strConexao);
conexaoBD.Open();
var result = conexaoBD.Query("Select Field1,Field2 from Table").First();
//access field value result.Field1
//access field value result.Field2
if (result.Field1 == "abc"){ dosomething}
Importing a spreadsheet I have filled a DataTable object with that data and returns expected results.
Attempting to put this into a format I can easily query to search for problem records I have done the following
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select row["Order"].ToString();
}
Works as expected giving me a list of orders. However I cannot add other fields to this EnumerableRowCollection. Attempting to add other fields as follows gives me an error
public void Something(DataTable dt)
{
// row["Version"] throws an error on me
var data = from row in dt.AsEnumerable()
select row["Order"].ToString(), row["Version"].ToString();
}
Error: "A local variable named 'row' cannot be declared in this scope because it would give a different meaning to 'row' which is already used in a 'child' scope to donate something else"
I'm thinking I need to alias the column name but I'm having no luck. What am I missing here?
It sounds like you're writing a bad select statement. Try the following:
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select new {
Order = row["Order"].ToString(),
Something = row["Something"].ToString(),
Customer = row["Customer"].ToString(),
Address = row["Address"].ToString()
};
}
That will create a new collection of Anonymously Typed objects that you can iterate over and use as needed. Keep in mind, though, that you want be able to return data from the function. If you need that functionality, you need to create a concrete type to use (in place of anonymous types).
I think you should use select new like this query for example:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
You probably want the following.
var data = from row
in dt.AsEnumerable()
select new { Order = row["Order"].ToString(), Version = row["Version"].ToString() };