简体   繁体   中英

Select on collection - C#

Say I have a sql query

SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users

Now say the records are now either in dictionary base or a strongly typed collection.

I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.

Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.

This is a test project as I am getting familiar with the web world wqith VS-2008

Perhaps LINQ and an anonymous class could do the trick for you.

from user in UserCollection
select new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn }

You can specify what columns you want to display in the gridview. Just specify the columns you want in the aspx page:

<asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" >
<columns>
<asp:BoundField DataField="firstname" HeaderText="First Name" />
<asp:BoundField DataField="lastname" HeaderText="Last Name" />
<asp:BoundField DataField="hiredate" HeaderText="Date Hired" />
</columns>
</asp:GridView> 

You can use linq to return an anonymous type (AKA tuple). That tuple would contain only the properties you are looking for. Then you can bind your grid to that collection. Google anonymous types or tuples in C# to see what I mean.

Assuming your data is in some form of IENumerable<T>:

var filteredUser = from U in Users
    select new { U.fname, U.lname, U.dob, U.SSN };

FilteredUser is now a collection with just those properties.

This is part of the cool thing about LINQ To Objects. You don't need to use LINQ-To-SQL to get your data, you can use anything you want to populate your initial question, and then use Linq-To-Objects to prune it down in memory.

You could use linq for what you need. If you have created a dbml for your data then you could just use LINQ to pull the records straight from the db(or if your collection is IEnumerable), like so:

Dim _records = From user in users _
               Select New With {.FirstName = user.fname,_
               .Lastname = user.lname,.dob = user.dob,.ssn = user.ssn}

{gridcontrol}.datasource = _records

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM