Linq select columns

Linq select columns DEFAULT

Select multiple columns in a LINQ query

LINQ is useful for querying as we can query different types of lists in C# or any other .NET language.We can select values from a list using Select operator in LINQ.But sometimes we need to project or select multiple columns or fields in a collection.

Suppose we have a List of items and we want want search some values in the list.We can easily do that using LINQ select operator
For example if we have an Employee class declared as:

class Employee { public string Name { get; set; } public string Id { get; set; } public string Dept { get; set; } }

we have list of employees declared as:

var employeesLst = new List<Employee> { new Employee { Name = "emp1", Id = "1",Dept="Accounts" }, new Employee { Name = "emp2", Id = "2",Dept="Finance" }, new Employee { Name = "emp3", Id = "3",Dept="Finance" }, };

then we can filter the employees based on the Id

var selectedLst=from item in employeesLst select item.Name;

But if now we want to select multiple Dept and Name fields then we can not use this since this will be invalid syntax in LINQ:

var selectedLst=from item in employeesLst select item.Id,item.Name;

to handle such scenario we can use the anonymous type using the following syntax:

var selectedLst=from item in employeesLst select new { item.Id, item.Name };

 

Filed Under: C#, LINQ Tutorial

Sours: https://codecompiled.com/select-multiple-columns-in-a-linq-query

How to select some specific column in Lambda Expression LINQ in Entity framework [Answered] RSS

Thank You Mr. Fei Han

I am new to Entity Framework so i have some confusion to creating LINQ Lambda Queries,According to your solution i changed return type of Method to List<Master_ReportFiles>

but still i am getting same error, actually i need to bind this List to GridView Control,so how properly it can be achieved, please help me for final solution. here is my code again with little changes as according to your suggession

internal List<Master_ReportFiles> GetAll(Master_ReportFiles obj) { ArrayList arr = new ArrayList(); DBEntities _entity = new DBEntities(); IQueryable<Master_ReportFiles> custQuery = _entity.Master_ReportFiles.AsQueryable<Master_ReportFiles>(); if (obj.RecordID > 0) { custQuery = custQuery.Where(c => c.RecordID == obj.RecordID); } if (obj.Project_Code > 0) { custQuery = custQuery.Where(c => c.Project_Code == obj.Project_Code); } if (obj.Month>0) { custQuery = custQuery.Where(c => c.Month == obj.Month); } if (obj.Year > 0) { custQuery = custQuery.Where(c => c.Year == obj.Year); } if (obj.ReportType > 0) { custQuery = custQuery.Where(c => c.ReportType == obj.ReportType); } return custQuery.Select(column => new MReportFiles { RecordID = column.RecordID, ReportName = column.ReportName, ReportType = column.ReportType + "-" + column.Month + "-" + column.Year }).ToList(); } } public class MReportFiles { public int RecordID; public string ReportName; public string Month; public string Year; public string ReportType; }

I am getting same Error 13 Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.IList<Model.Master_ReportFiles>'.

on .ToList()

Thank You

Sours: https://forums.asp.net/t/2011108.aspx?How+to+select+some+specific+column+in+Lambda+Expression+LINQ+in+Entity+framework+
  1. Turner falls cabins
  2. Kitco news
  3. Find the perimeter
  4. Compact tractors for sale ebay
  5. Custom chinese swords

Selecting specific columns in LINQ

To get going, open Data Search → Explore Your Data and click on the Free Text Query option. Here you can build your query using LINQ.

To simplify your query execution, Devo allows you to run a query with a shortcut when using your keyboard: CTRL+Enter for PC users and CMD+Enter for Mac users. Hover your mouse over the Run button to see the shortcut.

In this example the data table isand you only want the and columns.

Enter and the table name, followed by  and the columns you want to appear. If needed, remember that you may add a new name to the column using the operator . If you don't know the column names, or the table has a large number of columns, click on the Show Table Fields button and the list of columns will appear on the right.

Use the filter to search for the names of the columns if you cannot see them at a glance. Clicking on the headings Name and Type will organize them into their respective alphabetical order.

Alternatively, you can give new names to the columns using the operator . The columns will only appear in the search window under their new names:

Uncheck the Select All Fields option in the bottom right of the query if you only want to show the selected columns. This option is activated by default and will display all of the table's columns in the search window, regardless of the columns you select to display.

Below you can see that—having unchecked Select All Fields—only the selected columns are displayed, which in this case are , , and .

Once the table is open, you can still modify the query to include tables you did not include earlier or exclude them in case you do not need them. All you need to do is open the Query code editor and use the syntax explained above. As in the Free Text Query, you can click on the Show Table Fields button to see all of the available columns in the data table.

Selecting only the required columns differs from running a query with a data table and later hiding columns. Using this method, you can only hide and display the columns that you have selected when running the initial query. Take a look below to see how this works.

Using the same logic, if you return to the table in the applied query operations bar you will notice that none of the columns from the original table will be displayed. This is because your original LINQ query specified that only certain information be shown.

Operations using the Free Text Query

Devo allows you to run operations directly from the Free Text Query, with the process functioning just like selecting specific columns in LINQ as detailed above.

You can run multiple operations at once but the data returned cannot be used for further operations, such as alerts, etc.

Uncheck the Select All Fields box in the bottom right if you only want to return the results of the operations, otherwise they will be added to new columns at the end of the table.

Duplicating columns

Leaving the Select All Fields option activated while simultaneously selecting specific columns will result in all of the table's columns being displayed, with the selected ones being duplicated at the end of the other columns. This function can be useful if you wish to duplicate the information contained in a certain column and display it under a different name. In that case, you can enter the following free text query:

The original columns will still be displayed but the duplicates, under their new names, will appear near the very end of the query. In this example, we again use the table and want to rename the column as when and the column as how. We leave Select All Fields activated.

If you open a data table using the Finder option without selecting any columns, then all of the columns are shown in the search window. Therefore, if you later select a column using the Query code editor this simply creates a duplicate which is added at the end of the other columns. You can use this function as above to duplicate existing columns and give them new names.

Sours: https://docs.devo.com/confluence/ndt/searching-data/accessing-data-tables/run-a-search-with-selected-columns-only/selecting-specific-columns-in-linq
C# Essentials: Linq for Lists - Sorting, Filtering, and Aggregating Lists Easily

One of the most frequent complaints that I hear when presenting to DBAs about Entity Framework is that it’s “slow” and that “developers should be endlessly tortured for using it”. Ok, the second part I just made up but the sentiment exists. DBAs just don’t like developers using Entity Framework and with good reason. Entity Framework can make SQL Server work awfully hard if the developer isn’t careful. No, it’s not AprilFool’sDay, we’re really going to go over some Entity Framework code. But I promise you it won’t hurt…much.

One of the biggest problems that I’ve seen developers make is retrieving too many columns in a call to the database. I know what you’re thinking, “Why in the world would they retrieve more columns than they need?” Well, because it’s easy.

Let’s try and get all of the rows in a table using Entity Framework.

using(varcontext=newStackOverflowContext())
varposts=context.Posts;
// Do something with the data returned;

The context object allows interaction with the database. Stuff like getting data from the database, saving data to the database, and putting data into objects. This line Is where the magic happens:

varposts=context.Posts;

This one little line tells Entity Framework to go to the Posts table in the StackOverflow database, get ALL of the rows, and put them into C# objects. No SQL statement. No loading of data into business objects. Just one line and we have data from the database in the programmatic objects that we need them in. Super easy.

Of course, returning all of the rows from a table isn’t what your developers are probably doing but let’s see what kind of SQL Entity Framework generates from that one statement.

[Extent1].[AcceptedAnswerId]AS[AcceptedAnswerId],
[Extent1].[AnswerCount]AS[AnswerCount],
[Extent1].[Body]AS[Body],
[Extent1].[ClosedDate]AS[ClosedDate],
[Extent1].[CommentCount]AS[CommentCount],
[Extent1].[CommunityOwnedDate]AS[CommunityOwnedDate],
[Extent1].[CreationDate]AS[CreationDate],
[Extent1].[FavoriteCount]AS[FavoriteCount],
[Extent1].[LastActivityDate]AS[LastActivityDate],
[Extent1].[LastEditDate]AS[LastEditDate],
[Extent1].[LastEditorDisplayName]AS[LastEditorDisplayName],
[Extent1].[LastEditorUserId]AS[LastEditorUserId],
[Extent1].[OwnerUserId]AS[OwnerUserId],
[Extent1].[ParentId]AS[ParentId],
[Extent1].[PostTypeId]AS[PostTypeId],
[Extent1].[Score]AS[Score],
[Extent1].[Tags]AS[Tags],
[Extent1].[Title]AS[Title],
[Extent1].[ViewCount]AS[ViewCount],
[Extent1].[TagsVarchar]AS[TagsVarchar]
FROM[dbo].[Posts]AS[Extent1]

In case you were wondering, yes, this is every column from the Posts table. So in one simple, statement we generated a query that moves a ton of data that you probably don’t need. And let’s not talk about the additional CPU, I/O and the full scan of the clustered index that probably just happened.

Let’s take a look at a more real world example.

using(varcontext=newStackOverflowContext())
    varposts=context.Posts
                       .Where(p=>p.Tags=="<sql-server>")
                       .Select(p=>p);
    // Do something;

This one’s a bit more tricky but let’s walk through it. We’re getting data from the Posts table where the Tags column equals “<sql-server>” and selecting every column from the Posts table. We can tell because there are no specified properties in the Select. Even though this statement looks more complex it’s only three lines and looks somewhat like a SQL statement. But it’s really a LINQ (Language Integrated Query) statement, specifically a LINQ to Entities statement. This LINQ statement will be translated into this SQL statement:

[Extent1].[AcceptedAnswerId]AS[AcceptedAnswerId],
[Extent1].[AnswerCount]AS[AnswerCount],
[Extent1].[Body]AS[Body],
[Extent1].[ClosedDate]AS[ClosedDate],
[Extent1].[CommentCount]AS[CommentCount],
[Extent1].[CommunityOwnedDate]AS[CommunityOwnedDate],
[Extent1].[CreationDate]AS[CreationDate],
[Extent1].[FavoriteCount]AS[FavoriteCount],
[Extent1].[LastActivityDate]AS[LastActivityDate],
[Extent1].[LastEditDate]AS[LastEditDate],
[Extent1].[LastEditorDisplayName]AS[LastEditorDisplayName],
[Extent1].[LastEditorUserId]AS[LastEditorUserId],
[Extent1].[OwnerUserId]AS[OwnerUserId],
[Extent1].[ParentId]AS[ParentId],
[Extent1].[PostTypeId]AS[PostTypeId],
[Extent1].[Score]AS[Score],
[Extent1].[Tags]AS[Tags],
[Extent1].[Title]AS[Title],
[Extent1].[ViewCount]AS[ViewCount],
[Extent1].[TagsVarchar]AS[TagsVarchar]
FROM[dbo].[Posts]AS[Extent1]
WHEREN'<sql-server>'=[Extent1].[Tags]

See what I mean? The real question is “Do we need all of those columns?” Sometimes, the answer is “Yes” and that’s fine. But what if it’s “No”? How can we specify columns in our query? One easy way is to specify an anonymous type. Don’t be confused by the $2 word wizardry. Just think of an anonymous types as a way to put data into an object without defining an object. We can do that simply by using the “new” operator and selecting the properties from the object that we need. In this case, we only want to retrieve the Id and Title columns.

using(varcontext=newStackOverflowContext())
    varposts=context.Posts
                       .Where(p=>p.Tags=="<sql-server>")
                       .Select(p=>new{p.Id,p.Title});
    // Do something;

And the SQL generated:

[Extent1].[Title]AS[Title]
FROM[dbo].[Posts]AS[Extent1]
WHEREN'<sql-server>'=[Extent1].[Tags]

There. That looks better. But what if the developer needed a strongly typed object returned in the query? We can do this seamlessly by defining the class for the object and calling it in the SELECT. These types of objects are commonly referred to as Data Transfer Objects or DTOs.

    publicintPostId{get;set;}
    publicstringPostTitle{get;set;}
staticvoidBlogQueryDto()
    using(varcontext=newStackOverflowContext())
    {
        varposts=context.Posts
                           .Where(p=>p.Tags=="<sql-server>")
                           .Select(p=>newPostDto()
                           {
                               PostId=p.Id,
                               PostTitle=p.Title
                           });
        // Do Something
    }

In case you were wondering, using a DTO will not change the SQL that’s generated.

That’s it. Now you can dig into some code and help tune those pesky Entity Framework queries.

Sours: https://www.brentozar.com/archive/2016/09/select-specific-columns-entity-framework-query/

Columns linq select

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the for querying (it's not obvious that is an instance or the type name from your query):

Apparently, the class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

You can freely swap with here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

Note that in all of these cases, the is statically typed (it's type is known at compile time). The latter type is a of a compiler generated anonymous class similar to the class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a (which might or might not be the best thing to do), you can do this:

You can merge the above statements too, but I separated them for clarity.

Sours: https://stackoverflow.com/questions/1094931/linq-to-sql-how-to-select-specific-columns-and-return-strongly-typed-list
Part 9 Difference between Select and SelectMany in LINQ

LINQ to SQL - How to select specific columns and return strongly typed list

Basically you are doing it the right way. However, you should use an instance of the for querying (it's not obvious that is an instance or the type name from your query):

Apparently, the class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

You can freely swap with here without affecting anything (as this is what the compiler does).

Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

Note that in all of these cases, the is statically typed (it's type is known at compile time). The latter type is a of a compiler generated anonymous class similar to the class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

UPDATE:

If you really want to return a (which might or might not be the best thing to do), you can do this:

You can merge the above statements too, but I separated them for clarity.


The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!


Make a call to the DB searching with myid (Id of the row) and get back specific columns:

Sours: https://newbedev.com/linq-to-sql-how-to-select-specific-columns-and-return-strongly-typed-list

Now discussing:

So ticklish. - Do you like. - Yes.



3605 3606 3607 3608 3609