Read all rows of a specific column using LINQ - c#

Sounds trivial but I cannot find an elegant answer to this: how do I read all rows of a specific column into a list of strings for instance using LINQ on Entity Framework context?

You could try something as simple as the following:
var rows = dbContext.TableName.Select(x=>x.ColumName);
where dbContext is the class you use to "talk" with your database, TableName is the name of the table, whose column values you want to read and ColumnName is the name of the column.
Furthermore, if you place a ToList after the Select, you will create list of objects whose type would be the type of the values in column called ColumnName.

Christos answer will just give you an IQueryable. If you want an actual List you need to do something with the IQueryable:
var rows = dbContext.TableName.Select(x=>x.ColumName).ToList();
though I might go for the LINQ syntax:
var rows = (from c in dbContext.TableName
select c.ColumnName).ToList();
The two forms are equivalent.

Related

Linq Contains Query from Table List

I have a table with a list of keywords like
Waiter
Receptionist
Cleaner
Painter
And I have another table that has a Job Title.
I want a query that tells me if any of the words in the first table are contained in a specific Job Title in the second table
Im wondering if this is possible without looping over every row in the first table.
Use this as reference and modify as needed.
SecondTable.Where(a => FirstTable.Any(b => b.Keyword == a.Keyword))

is there a better performance's way to get only few columns in ASP MVC without getting the whole table and filter it with LinQ?

im calling a table with 200.000 rows and 6 columns, but i only want 2 of these columns to be used in one controller, so i want to know if there is a better way to call them from the server without compromising performance, because as i know Linq queries get the whole table and them makes the filtering, i think maybe Views is a good way, but i want to know if there are others and betters, Thanks.
for example:
var items = from i in db.Items select new {i.id,i.name};
in case i have 1.000.000 items, will it be a trouble for the server?
Your initial assumption is incorrect.
In general LINQ queries do not get the whole table. the query is converted into a "server side expression" (i.e. a SQL statement) and the statement is resolved on the server and only the requested data is returned.
Given the statement you provided you will return only two columns but you will get 1,000,000 objects in the result if you do not do any filtering. But that isn't a problem with LINQ, that's a problem with you not filtering. If you included a where clause you would only get the rows you requested.
var items = from i in db.Items
where i.Whatever == SomeValue
select new { i.id, i.name };
Your original query would be translated (roughly) into the following SQL:
SELECT id, name FROM Items
You didn't include a where clause so you're going to get everything.
With the version that included a where clause you'd get the following SQL generated:
SELECT id, name FROM Items WHERE Whatever = SomeValue
Only the rows that match the condition would be returned to your application and converted into objects.

Dynamic where clause in linq query

Sorry for my bad English. I have a problem. I want to create dynamic where clause in a LINQ query. I have one list object name "list1" having values Country, City, State and one datatable that has column named Name, Lastname, Country, City, State. I want to compare list1 values with datatable columns and get null / empty rows.
So I want a LINQ query like this:
var query = from p in datatable.AsEnumerable()
where list1 == null
select p
but it returns an error. How can I solve this problem?
Thanks in advance.
Ok, let's get going - your query is ridiculously bad.
You should not have datatable.AsEnumerable - that forces a table scan (running through the whole table).
Second, you have to code all fields expressively. This is going to get nasty - per definition Depending on size of list this will be very bad.
In general, every query is an IQueryable itself, so you can chain where conditions.VERY nice - I use that partially myself, defining the core query, then adding additional where clauses as needed (by input parameter) before executing.
Sadly, comparing a table against a list of elements by individual field match is as bad as it gets from the sql level.

SubSonic .Paged() query returns duplicate records

Using a SubSonic (2.2) SqlQuery object, I am querying a view that contains distinct rows from another table. The results of the query, however, contain multiple rows for certain rows in the view. It appears to be because of a join on a temporary table in the query generated to achieve paging. How can I avoid this duplication of rows?
Bonus points: I have to use the view because SubSonic can't do .Paged() and .Distinct() at the same time. Why not?
If I remember correctly you have to use distinct on the right position.
var query = DB.Select().From<Products>()
.Where(Products.CategoryColumn).IsEqualTo(5).Distinct();
var query = DB.Select().Distinct().From<Products>()
.Where(Products.CategoryColumn).IsEqualTo(5);
Both statements compile but the first generates invalid sql code. A good starting point for debugging SubSonic SqlQueries is to generate the output:
var sql = query.BuildSqlStatement();
Another solution could be to use Group instead of distinct so you can avoid the view in the first place.

Select column based on variable in LINQ to SQL

I'm using LINQ to SQL in C# in my application. I need to be able to select a column of a row, depending upon a variable. This is easy for the row as it's a simple where clause, but I'm at a loss with only selecting a specific column. Here is my code so far:
var permissions = (from s in dc.Permissions where s.dashboardname == permission select s.[variablehere]).Single();
Is this easy to accomplish?
Is it possible to change your database structure so that your columns becomes rows? (Pivot your table?)
Eg.
Permissions Table
-----------------
Id
Dashboardname
Page1
Page2
Page3
...
and turn it into
Permissions Table
-----------------
Id
Dashboardname
Pagename
Then you could use the where clause to select the row you want?
I'm not sure that I understand your question completely, so this might be a bit off. But could your problem perhaps be solved by using the LINQ Dynamic Query Library?
You can use the DynamicQuery library
against any LINQ data provider
(including LINQ to SQL, LINQ to
Objects, LINQ to XML, LINQ to
Entities, LINQ to SharePoint, LINQ to
TerraServer, etc). Instead of using
language operators or type-safe lambda
extension methods to construct your
LINQ queries, the dynamic query
library provides you with string based
extension methods that you can pass
any string expression into.
See the above link for samples and downloads.
I don't think this is either possible or a good practice. Note that if the variable name is provided by user he or she can easily take all the data they want. Maybe you should try using enumeration and switch() clause?
Say the class that holds the permissions is named Permission, you can define an extension method:
public static class PermissionExtensions
{
public static object SelectProperty(this Permission obj, string variable)
{
return obj.GetType().GetProperty(variable).GetValue(obj, null);
}
}
You can use this in your query like this:
(from s in dc.Permissions where s.dashboardname == permission select s)
.Single().SelectProperty(variable);
This doesn't select the property in the query but instead gets it from the instance.
Another answer that came in my mind is to create table with key-value pairs i.e.
dashboard
key
value
where primary key is (dashboard, key).

Categories

Resources