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
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>
source to share
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.
source to share
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
source to share