.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

C#, LINQ: (List<>) Question???

Posted By:      Posted Date: August 21, 2010    Points: 0   Category :ASP.Net

Hi Everyone,

I have a strange problem:


There is an entity (Table) called "Filters" in my .edmx which has all my tables and stuff in it (to use it for LINQ queries)

I have created a class called "CustomFilters" which inherits "Filters". So now my cutom class has all the properties of the original "Filters" class (table) and 1 more additional property that i wanted which is a List of "CustomFilters":

List<CustomFilters> children = new List<CustomFilters>();

Now i get all my records into:

List<CustomFilters> theOriginalList = new List<CustomFilters>();

NOTE: first all records are tken into a List<Filters> and then these are added into List<CustomFilters> where List<CustomFilters> for children of that record is added, and then children of the child records, and so on......

so now, every record is an instance of CustomFilters which has a property named "children" which is a list again; and each child again has instanaces of "CustomFilters", and each instance again has children...and on and on and on.....

(basiacally its a data source for a treeview in my silverlight control)

every thing is good and working as expected.


View Complete Post

More Related Resource Links

MVC Linq Join List Question


This is the query I have

    Function Index() As ActionResult

            ViewBag.dateNow = DateTime.Now

            Dim result = (From newLocation In DataAccess.Locations Join
                         newState In DataAccess.States
                         On newLocation.state Equals newState.id
                         Select newLocation, newState)

            '   Return View(DataAccess.Locations.ToList)
            Return View(result.tolist)

        End Function

I am trying to populate the ToList View, but I can't figure out how to call a specific column since it is using a join...

Example:   @item.address

I was thinking it would be like   @item.newlocation.address

However, that is not working --- any advice?

Query an arraylist of array list using linq


I have an array list called Customer. I t holds a list of array list which has the account details.

proj.customer -> collection of arraylist of type customer

proj.customer.account -> collection of arraylist of type account

Account array list holds type account and it has a poperty account balance. How can I query all accounts which has account balance  >100

I tried the following one

var Accountlist= from Account accountdetails in proj.customer.account

where accountid.balance >100

select accountdetails.id

But it is always throwing an error saying cannot cast type customer to type account

Please help

Linq query results to List collection



I have a GridView in my page. I want to use below code in code beind. query nothwing DB using linq . add linq query result to new list and then bind list as gridview Datasource

I use below code . But I don't know how to add results to List? Could any one tell me how !

Public Class OrderCity
        Private _name As String
        Private _city As String
        Public Property name As String
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value

            End Set
        End Property
        Public Property city As String
                Return _city
            End Get
            Set(ByVal value As String)
                _city = value

            End Set
        End Property
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dbe As New SFFAV1DataContext
        Dim latestadsDs = From p In dbe.Products _
                            Select New With {p.Title, p.ProducedCity} _
                             Take (2)

        Dim FilteredList As New List(Of OrderCity)()
        For Each result In latestadsDs
            Dim Menedfcou = Nothing
            FilteredList.Insert(0, Menedfcou)

How to handle null while converting from my datatable to List<> using LINQ


I am converting my datatable to LISt using LINQ
how do I handle nulls coming from database

List<Port> portDetails = new List<Port>();
DataTable dt = ds.Tables[0];               
portDetails = (from q in dt.AsEnumerable()
select new Port
PortCode = q.Field<string>("Code"),
ExtCode = q.Field<string>("Nb"),
Name = q.Field<string>("Name"))

In the above query if Code is null I do not want property
portcode to be set to the value it should only set if it is
not null or not blank 
PortCode = q.Field<string>("Code"),

What should be syntax
I was trying somethign like this which doesnt work
Portcode = q.Field<bool>("Code") == null ? null : q.Field<bool>("Code")


Noob Question - Using Linq in View

I just inherited an MVC2 application. So far my only experience with MVC is reading the Nerd Dinner sample chapter and downloading the nerd dinner app. I do plan to dive much deeper but i need a quick answer because i have to hit the ground running. So basically in the main Index view the view model is being passed as an IQueryable. Then he is doing some queries on the view model to loop through the data. See example below:<% if (Model.Where(w => w.State == workflowStep.Key).Count() > 0) { %>To me, even though minor, this is business logic and shouldn't be in the view. Shouldn't any type of logic like this be sorted out before you get to the view? Or is this common practice in MVC?Basically i want to know if I should spend time refactoring this thing or just go with the flow.  Thanks.

Question about List Tools ribbon

Hi, is it possible to set by default to visible the "List Tools" upon the ribbon. When I go to Task list, the List Tools is visible by default but not with my custom lists.

Compile issue with List<> and Linq

I am pretty sure this is some framework version issue but I am getting this on a (custom layout) page compile migrated over from MOSS. The following code complies in my MOSS 2007 environment but does not in my new 2010 environment. Thanks in advance for any help. Code section #1: private bool isSuccessReturnCode(string s) { bool bReturn = false; // Following line fails looking for ';' XDocument loaded = XDocument.Parse(s); var q = from c in loaded.Descendants("Node") select (string)c.Element("ReturnCode");   Code Section #2 private InvoiceItem getInvoiceItem(Guid ID) { List<InvoiceItem> InvoiceItems = ((List<InvoiceItem>)ViewState["INVOICEITEMS"]);

Insert a "Select User" row in Linq for a dropdown list

I'm new to Linq. I have searched and searched the web for a soluion, and can't find anything. I have a Linq query and I want to insert a row ("Select User") to the top before I pass it to the drop down list. I've been trying to use the Union but to now avail (it keeps telling me that my object doesn't support the Union method). My code, prior to attempting to inser a row, is very simple.public SelectList DropDown_Users()        {            var context = new VivarianDataContext();            var query = from t in context.AspnetUsers                        select new { t.UserId, t.LastName };            list = new SelectList(query.AsEnumerable(), "UserId", "LastName");            return list;        }Now I try to insert a row and I found this on the internet and it seems to say that his solution will work. But it is filled with syntax errors. http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-met

Linq to SQL - DeferredLoadingEnabled/DataLoadOptions Question

I am reading a book that suggests that when you need data from a child table that you should both: Set DeferredLoadingEnabled to false and Set the DataLoadOptions This seems a bit redundant to me.  If DeferredLoadingEnabled is false, why would you need to set the DataLoadOptions?  Doesn't turning off deferred loading mean that the child tables will automatically get loaded when the query is executed? Thanks

LINQ left outer join question

I can do this in other ways, but am looking for the "LINQ" way of doing this: Table1: People (PersonId,SchoolId)Table2: AssignedPeople (PersonId,SchoolId,RoomId) I want to select the people in Table1 within a particular SchoolId that are not in the assignedPeople table (in a particular Room).  The SQL is: select p.* from people p left outer join assignedpeople ap on p.PersonId=ap.Person and p.SchoolId=ap.SchoolIdand ap.RoomId=@roomId where p.SchoolId=@SchoolId and ap.PersonId is null I tried this LINQ (VB,NET):dim SchoolID as guid=...dim RoomID as guid=... (from p in dc.people where p.SchoolId=SchoolIdgroup join ap in dc.AssignedPeopleon p.PersonId equals ap.PersonId and p.SchoolId equals ap.SchoolId into groupfrom g in group.DefaultIfEmptywhere g.RoomID = nothing) but I can't get the ap.RoomId=@roomId part into the right place, should be something like:group join (from ap in dc.AssignedPeople where ap.RoomId=RoomId) Any help would be appreciated,Reuven

Simple question.... LINQ on Datatable

Hi all,Simple one this I am sure for those who use LINQ! :)I basically have two tables that will be stored in viewstate until I save the data to the database.  I need a way to query the datatables, delete remove etc.  Is this possible in LINQ?So for example, delete/select rows from the DataTable that have a particular ID etc...Thanks,Mark

How to update List Items with LINQ?

In the code below, the For Each will loop through the list and populate the ListBox.  When I add "item.LeadTime = 5" to try updating an item, Visual Studio says that it is ReadOnly.  Any ideas on what's wrong or missing from the code? Dim spWebUrl As String = SPContext.Current.Web.Url Dim dc As New MyDataContext(spWebUrl) Dim Asgns = From a In dc.GetList(Of AssignmentsItem)("Assignments") Select a.LeadTime, a.Frequency For Each item In Asgns      ListBox1.Items.Add(item.Frequency)      item.LeadTime = 5      dc.SubmitChanges() Next  

Question on WCF service with Linq to SQL on 64-bit system

I'm trying this question one more time since I realized the work in in a 64-bit environment. I have a WCF service which runs in production in a 32-bit environment using VS2008 and .NET 2.0. We made a big change to our environment (lots at the same time) and I moved the services to VS2010, .NET 4.0, and 64-bit processes.  I wrote a new service and deployed it under IIS.  If I browse to the service I get the example screen and clicking on the link gives me the metadata.  So all of that is working. In my services I create a Linq to SQL context, perform a query, then return the result set as an Array.  I wrapped the context creation with a using.  My tests returned an exception "Attempt to access an object that has already been disposed".  I traced it down and found that the code executes, forces the query, returns the results, exits the using statement (disposing the context properly) then exits the method.  The next thing I get is the exception, inside framework code, and it is linq code attempting to fulfill the query once again. I have searched until I'm blue in the face trying to find prior incidents and fixes but all I found was one post, two years ago, same problem with less debugging, and no answer to the problem other than 'don't use the using statement' which is a bad suggestion.  So for a work around I wrote a Co

Using LINQ to Get Filtered List of Controls


I have zero experience with LINQ but had occasion to use it today.  I implemented a working solution but do have a question.

First, let me provide the background:

I have 20 large web pages that altogether have several hundred data input controls on them.  There are strong similarities between how each type of control is handled.  Rather than wire up each control individually (ie. hard code it in the layout page), I thought it would be a lot easier to just do so dynamically through a common method.  On each of these web pages there's a MultiView control, inside of which are 2+ View controls.  The guts of my original version of the common method looked like this:

      foreach (View view in multiView.Controls)
        foreach (Control ctrl in view.Controls)
          switch (ctrl.GetType().Name)
            case "DropDownList":
              DropDownList ddList = (DropDownList)ctrl;

LINQ TO SQL question


Background: I took over a project that I have to upgrade and I had a performance/suggestion question for the group.  I have a table of customers {id, name} and a table of contact information {id, fkcustomersid, data, type, default}.

Each record in the contactinformation table has a realtionship with the customers table (fkcustomerid), either an email or phone number (data), A type describing what is stored in the data column 'Email' or 'Phone' (type), and 1 or 0 denoting whether this contact record is their default email or default phone (default). 

I need to pull back a grid that in each row has the customers name, their default email, and their default phone. 

The problem I am running into is that the customer can have 0 or many emails and 0 or many phone numbers, so I have not been able to come up with a join statement (or simple linq query that only queries the database once) to return one row containing the customerID, customer name, default email (if available), default phone number (if available). 

Right now, I have this setup in linq like this:

var customers = from c in db.tblCustomers
                        select c;

foreach (var customer in customers)
     dr[0] = customer.ID;
     dr[1] = customer.Name;
     var defaultPhone = db.tblContactInfo.SingleOrD

List - easy question hopefully :)


Hi there,

Sorry in advance if this is the wrong place to post. Please redirect me if necessary.

I have a Generics list of my class objects - at any given time there could be a maximum range of 100 to 1000 objects in my generics list of objects. 

Let's say I have just 3 MyObject in my generics list. I want to do a .RemoveAt(0) because I no longer need it, and then maybe do a couple of .Add(MyObject) methods and then another .RemoveAt(0) method call. 

In other words, there will be constant .RemovingAt index zero and .Add method calls - the question is: I am worried about memory since the Generics list is in constant reindexing flux. Do I have anything to worry about given this scenario???

The MyObject is a very small class.


Simple LINQ to SQL question


Someone help me with what I'm missing here...

I have a VERY simple file as you can see... just three tables.


The Problem is that if I do this somethign like this....

var patients = from x in db.CT_Patients
                     where x.CT_Visits...... (error here)


It doesn't display child properties for CT_Visits from CT_Patient like it should. I only get the standard LINQ queries like Select, Where, Orderby etc... What am I missing???


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend