Select in collection - C #
Let's say I have a sql query
SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users
Now let's say that the records are now either in the dictionary base or in a strongly typed collection.
I have a grid control and I want to bind it to my collection, but I only want to display fname, lname, dob and ssn and not other columns.
Is there an easy way to fetch columns and then bind to the retrieved item? Not sure if LINQ would be helpful here.
This is a test project as I am familiar with the wcith VS-2008 web world
Maybe LINQ and anonymous class can 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 which columns you want to display in the gridview. Just specify the columns you want on 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). This tuple will only contain the properties you are looking for. Then you can bind your grid to this 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 these 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 whatever you want, fill in your initial question and then use Linq-To-Objects to shrink it in memory.
You can use linq for whatever you need. If you've created a dbml for your data, you can simply use LINQ to pull records directly 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