I have a webservice that returns DataTable, but instead of it I want to return a list. Is there a way to return a list directly from SQL or I would have to return it as a DataTable and then transform it to a list?
What you want to do is convert each row in your DataTable to an object.
Here is a nice blog post that shows a helper class for this: Converting Custom Collections To and From DataTable
The idea is that you loop trough all your rows and then use reflection to create the objects. You do this by mapping each column name to a corresponding property name.
You can also use Linq to DataSet to run a Linq query against your DataTable. In Linq you can then use Projection to transform your data into a new type.
Here are some examples: Query Expression Syntax Examples: Projection (LINQ to DataSet)
Related
In Room 2.4, there is a new feature called relational query method in DAO which you can write your custom query to select columns from 2 entities and Room can be able to aggregate into Map<TableA, List<TableB>> return type.
I have a fairly complicated query which do left join with nested queries to return a map of railway stations and their associated rail lines (many-to-many relationship). I tried to make a #Query method returns Flow<Map<RailStation, List<RailLine>>> and it can return the map that I want.
Now, I want to go one step further to make it returns paging 3's PagingSource. As the original type is a Map, so I think I should make the paging #Query method as PagingSource<Int, Map.Entry<RailStation, List<RailLine>>>. (Map.Entry should be the representative type of a single list item rather than Map as it represent the whole query result.) However, the Room annotation processor complainted about this line saying that it cannot handle this type:
[ksp] RailStationDao.kt:130: Not sure how to convert a Cursor to this method's return type (androidx.paging.PagingSource<java.lang.Integer, java.util.Map.Entry<RailStation, java.util.List<RailLine>>>).
So my question is: does the Room annotation processor and Paging 3 support for relational query method with paging 3? If not, is there any alternative way to archive the same goal? It seems like the #Relation annotation in Room can only support for simple table joining, but my case is I need to write nested query in the LEFT JOIN clause.
I am using gorm to interact with a postgres database. I'm trying to ORDER BY a query that uses DISTINCT ON and this question documents how it's not that easy to do that. So I need to end up with a query in the form of
SELECT * FROM (<subquery>) ORDER BY column;
At first glance it looks like I need to use db.QueryExpr() to turn the query I have into an expression and build another query around it. However it doesn't seem gorm has an easy way to directly specify the FROM clause. I tried using db.Model(expr) or db.Table(fmt.Sprint(expr)) but Model seems to be completely ignored and fmt.Sprint(expr) doesn't return exactly what I thought. Expressions contain a few private variables. If I could turn the original query into a completely parsed string then I could use db.Table(query) but I'm not sure if I can generate the query as a string without running it.
If I have a fully built gorm query, how can I wrap it in another query to do the ORDER BY I'm trying to do?
If you want to write raw SQL (including one that has a SQL subquery) that will be executed and the results added to an object using gorm, you can use the .Raw() and .Scan() methods:
query := `
SELECT sub.*
FROM (<subquery>) sub
ORDER BY sub.column;`
db.Raw(query).Scan(&result)
You pass a pointer reference to an object to .Scan() that is structured like the resulting rows, very similarly to how you would use .First(). .Raw() can also have data added to the query using ? in the query and adding the values as comma separated inputs to the function:
query := `
SELECT sub.*
FROM (<subquery>) sub
WHERE
sub.column1 = ?
AND sub.column2 = ?
ORDER BY sub.column;`
db.Raw(query, val1, val2).Scan(&result)
For more information on how to use the SQL builder, .Raw(), and .Scan() take a look at the examples in the documentation: http://gorm.io/advanced.html#sql-builder
I can log the underlying query of a linq query by simply using the ToString() method.
string raw = query.Where(..whatever..).ToString();
I need the exact underlying query for the FirstOrDefault() method
query.FirstOrDefault().ToString()
because we get a very bad performance for this query and we want to analyze it.
Here the ToString() method only returns the class name.
Is there a possibility to get the underlying query?
I am programming a Silverlight application in c#, which takes lists from a sharepoint.
I want the distinct elements from a specific column in the list.
After getting the query I can't handle with the var-datatype. The program exists everytime, when I want to make a datacast, for example in an ListItemCollection.
Here is the code:
ListItemCollection bla;
var result = bla.Select(m => m["Region"]).Distinct();
ListItemCollection a = (ListItemCollection)result; //Error happens here
LINQ deals with instances of IEnumerable<> or IQueryable<>. Distinct returns an IEnumerable<> or IQueryable<> depending on the type of the original collection. In your case, it returns an IQueryable
You are trying to cast that IQueryable to a ListItemCollection, which understandably results in an invalid cast exception.
You don't need to do something else to start working with the items. You can iterate over them with foreach, convert them to an array or list with ToArray() and ToList() etc
Linq provider for SharePoint does not support Distinct operator which is why this error occurs.
According to MSDN:
Some LINQ queries cannot be completely translated into CAML. However,
however such queries can, in principle, run correctly because they can
be executed in two stages. First, the LINQ to SharePoint provider
translates as much of the query into CAML as it can and executes that
query
Please refer Unsupported LINQ Queries and Two-stage Queries for a more details.
Two stage approach
To correct this error, you should cut your queries in two stages to force the first query execution before the second one. To do that, you should for example transform the first IEnumerable<T> in a list thanks to ToList() method.
The following example demonstrates how to return unique values from ListItemCollection object:
var result = items.ToList().Select(i => i["Region"].ToString()).Distinct(); //System.Linq.Enumerable.DistinctIterator<string> type
foreach (var item in result)
{
//...
}
I am new to Linq please guide me on some basic things.
In read some articles on Linq. Some authers fill data in var from Linq query, some fills list of custom type objects and some fills data in IEnumerable and some do it in IQuryable. I could not get what is difference in these 4 and which one should be used in which situation.
I want to use Linq to SQL. What should I use?
Well, you can never declare that a method returns var - it's only valid for local variables. It basically means "compiler, please infer the static type of this variable based on the expression on the right hand side of the assignment operator".
Usually a LINQ to Objects query will return an IEnumerable<T> if it's returning a sequence of some kind, or just a single instance for things like First().
A LINQ to SQL or EF query will use IQueryable<T> if they want further query options to be able to build on the existing query, with the added bits being analyzed as part of the SQL building process. Alternatively, using IEnumerable<T> means any further processing is carried out client-side.
Rather than focusing on what return type to use, I suggest you read up on the core concepts of LINQ (and the language enhancements themselves, like var) - that way you'll get a better feel for why these options exist, and what their different use cases are.