Linq on a Datasource of list type - linq

I have several entity objects for eg. Customer, Orders which derive from IComparable
and all all mapped to database fields.
I bind the grid at runtime as a List<Customer>, List<Orders> etc.
I am writing a custom column class
where I can get Parent.DataSource (it would always be List<>) but the actual type is unknown. I need to convert that to a list type (maybe IList) so I could write linq queries against the datasource.
something like
IList t = Parent.DataSource as IList
var qry = from cl in t

You should be able to convert your Parent.DataSource into the appropriate type via LINQ's Cast() method, and query against it:
var query = from customer in Parent.DataSource.Cast<Customer>()
where customer.Foo == "Bar"
select customer;

you can use Cast in Linq .
var query = from customers in Parent.DataSource.Cast<Customer>()
select customers;
Cast<Customer> will convert your Parent.DataSource to your corresponding Customer entity

Related

How to obtain property name and types (by reflexion or better) of a linq result anonymous type

I need to obtain property names and types of a linq result (by reflection or better)...
I say better because I think linq should have a structure in every query with this info!!!
for example
I have a linq query like:
dim query1 = from e0 in clients select new { e0.id, e0.name }
I pass query1 as a parameter to a function, then I need to know how much properties there are in query1, the property names and the property types...
Thx, ZEE ;)
Type memberType = query1.GetType().GetGenericArguments()[0];
foreach (var a in query1)
{
foreach (PropertyInfo pi in memberType.GetProperties())
{
Console.WriteLine(pi.GetValue(a, null));
}
}
actually I will store the PropertyInfos in a List<PropertyInfo> and in the inner foreach, use the stored properties. But the above code is the simplest to understand.
First, you shouldn't be passing query results typed as a sequence of instances of an anonymous type to another method. If you're doing this, you should make a concrete class for the query results.
You can use reflection to tear out the properties from query1 as follows. query1 will implement IEnumerable<T> for some unique type T. Once you have this type, you can call
type.GetProperties()
to get an enumeration of the anonymous type member names.

Dynamic Linq - no property or field exists in type 'datarow'

I am using Northwind Customers Table where I fill the dataset and get the datatable.
I am trying to use dynamic linq and want to select columnName dynamically
var qry = MyDataTable.AsEnumerable().AsQueryable().Select("new(Country)");
Right now I have hard coded country but even then I get this error
No property or field 'Country' exists in type 'datarow'
I would like to eventually change this query to take the column name dynamically.
Please help!!! thanks.
The important hint is here (in bold):
No property or field 'Country' exists
in type 'datarow'
The extension method AsEnumerable of the DataTable class returns an IEnumerable<T> where T has the type DataRow. Now the Select method of Dynamic LINQ wants to work with this type DataRow which hasn't a property Country of course.
You could try this instead:
var qry = MyDataTable.AsEnumerable().AsQueryable()
.Select("new(it[\"Country\"] as CountryAlias)");
it now represents a variable of type DataRow and you can use methods of this type and perhaps also the indexer in my example above. (Dynamic LINQ supports accessing array elements by an integer index, but I am not sure though if accessing an indexer with a string key will work.)
I've used Slauma's answer and it worked. In addition i was doing OrderBy with dynamic linq maybe this will help to someone. I'll just drop the code here.
string dynamicLinqText = $"it[\"{sortColumnName}\"] {sortDirection}"; //it["PERSON_NAME"] asc
result = result.AsEnumerable().OrderBy(dynamicLinqText).CopyToDataTable();

How do I perform a dynamic select in Linq?

I am trying to figure out how to dynamically specify the properties for my select clause in a linq query.
Lets say I have a collection of employee objects. At run time, the end user will be specifying which properties they would like to see for those employees, so I need to be able to dynamically construct my Linq select clause.
I have used the dynamic Linq library, but I prefer not to use that, because it requires me to build a string to pass to the select method. I'd like to understand how to do this via Expressions.
This looks like something that fits more with your requirements of not using dynamic linq.
Use Reflection to get the dynamic Column Values
//columns variable has column name as comma separated String which you
can save in DB //example string columns ="Name,Id,Age";
var strColumns =columns.split(,);
foreach(var myObject in MyObjectcollection)
{
for(int index =0;index<strColumns.count();index++)
{
//Create a collection of objects
mycollection.add(myObject.GetType().GetProperty(strColumns[index]).GetValue(myObject, null));
}
}

Return Datatype of Linq Query Result

I think I'm missing something really basic.
var signatures=from person in db.People
where person.Active==true
select new{person.ID, person.Lname, person.Fname};
This linq query works, but I have no idea how to return the results as a public method of a class.
Examples always seem to show returning the whole entity (like IQueryable<People>), but in this case I only want to return a subset as SomeKindOfList<int, string, string>. Since I can't use var, what do I use?
Thanks!
You can get concrete types out of a linq query, but in your case you are constructing anonymous types by using
select new{person.ID, person.Lname, person.Fname};
If instead, you coded a class called "Person", and did this:
select new Person(peson.ID, person.Lname, person.Fname);
Your linq result (signatures) can be of type IEnumerable<Person>, and that is a type that you can return from your function.
Example:
IEnumerable<Person> signatures = from person in db.People
where person.Active==true
select new Person(person.ID, person.Lname, person.Fname);

LINQ: what is the type of a result?

I have a simple select from a typed dataset:
var productlist = from prds in dsProducts.sk_products.AsEnumerable()
join prdcat in dsProducts.sk_productscategories.AsEnumerable() on prds.Field<int>("productid") equals prdcat.Field<int>("productid") where prdcat.Field<int>("categoryid") == categoryid
select prds;
Where productlist is set of records from the Dataset's sk_products datatable.
I'd like to write a function to filter the records more, with a distinct on one of it's columns:
public List<string, string> GetDistinctManufacturerList(? productlist, int manufacturerid)
{
manufacturers = from prdz in productlist where prdz.Field<int>("manufacturerid") == manufacturerid select prdz; [...]
}
With what type of object should I refer to the variable productlist?
Its an IEnumberable<selected data type> - the selected data type could be an anonymous type, or in this case, will be your dataset type class.
I would guess something like IEnumerable<Product>. And as ck says, Product is the name of your LINQ data class.
In your first example... mouse-over the word "var" in Visual studio, and it will display the "Type".
If it's something like 'anonymouse{blahblah}'... then you'll likely have to create a class that you want to convert it to so that you can use it as a function parameter.

Resources