.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

LinQ Syntax of looping a collection

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

Hi, I would be glad is there is anyone can point/teach me the correct way of iterate a collection in LINQ. I attached part of my coding for reference. I wish to find out the location(s) of an Employee who can also happen to be a Supervisor. My model contains a Many-to-Many relationship between Location and Employee. Thanks in advance


Dim someDataSource = From _e As Employee In _context.Employees
                                  Where _e.Locations = location <---- _e.Locations return a collection 
                                  Select _e.FullName, _e.ID


View Complete Post

More Related Resource Links

Need Syntax To Make Results of LINQ Union Return Non-Generic Type



I have the below SQL which works just fine:

SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter

I have been going about trying to convert the above into a LINQ method and am having problems with return types.
As the above SQL illustrates, I am querying two distinct LINQ tables - Alerts and StatusUpdates -
and then attempting to perform a Union on them. In order to do the union in LINQ, I have to have agreeing types. So, I
am using "var" to make the results of "alerts" and "updates" generic before the union.  

public IList GetStatusUpdatesAsAlertsByAccountId<T>(Int32 accountId)
            using (WorkbookDataContext dc = _conn.GetCont

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)

LINQ Syntax

Hello,Before I am using SQL 2005.I use this method for table join select tbl_class.Class_Name,tbl_Class.Class_Section fromtbl_student,tbl_studentenrollment,tbl_batch,tbl_classwheretbl_student.Stu_ID = tbl_studentenrollment.Stu_IDandtbl_studentenrollment.Batch_ID = tbl_batch.Batch_IDandtbl_batch.Class_ID = tbl_class.Class_IDandtbl_student.Stu_Name = 'STUDENT NAME'Now I am using MVC in VS 2010I create .dbml file using MODEL and drag all tables on .dbml fileNow i want to perform above said query using LINQWhat Should Be Sayntax for above said query in LINQ ??? Help In this Matter Appreciated In Advance !

Get Distinct value from a Group-Join syntax Linq

Hello,I have this group-join syntax but I couldn't get the distinct value from the relational tables below.Table_1key_1 t1_value1     Food2     Sports3     Leisure 4     Trip5     ZooTable_2key_2   key_1  t2_boolean15        1          True16        1          True17        1          True18        2          True19        2          True20        2          Falsedesire result:FoodSports            Dim c = (From t1 In dbContext_Table_1 _                                     Group Join GroupTable In _db.Table_2 On GroupTable.key_1 Equals t1.key_1 Into Group 

LINQ to SQL "Incorrect syntax near the keyword 'WHERE'"


I am having a problem that creeps up over and over when using LINQ to SQL.  I am getting the error: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'.

Now I have done a great deal of digging, and the only cause I can seem to find is when users are overriding the Equals() or GetHasCode() methods of the generated classes.  I am not overriding either.  I am getting this error on two different project with two different databases.  I have tried everything every post I have found suggests.  I have even scrapped my dbml file and re-created, all to no avail.

Anyone have any thoughts?  They would be greatly appreciated!

Ryan Sakry
Program Manager
Retail Information Technology Enterprises

2010 Collection class syntax/property problem

I converted a project from 2008 to 2010 to be able to use the TPL.

I've updated the compile target to .NET 4. Everything seems good, including the .NET 4 specific TPL stuff...except that:

Parallel.ForEach(MyClassCollection.Cast(Of MyClass), (Sub(ANYTHING As MYClass) ANYTHING.MySubRoutine()))

Gives the following as a syntax error:

Error 2 'Cast' is not a member of 'Microsoft.VisualBasic.Collection'. C:\Users\jeff\Documents\Visual Studio 2010\Projects\MyProject\MyProject\RunLoop.vb 229 34 MyProject

Any ideas?


Help with Linq syntax



I'm having one of those brain-shuddering moments where I know the answer in SQL but can't get it quite right using LINQ to dataset - anyone help?

var deals =                                                      
    from m in dtM AS Enumerable()                  // first part of query
    select m.Field<Int32>("MerchantIdId")       // runs down a standard table or list (from d in dtD AS Enumerable()                 // sub query orderby d.Field<Int32>("Seq")   // returns first occurrence of a deal in table select d.Field<Int32>("DealId")).FirstOrDefault() // the two need bolting together so that for each record in dtM, I return the first // occurrence of DealId in dtD

Thanks in advance.

*** update ***

I suppose what i'm lookin is nearly the equivalent of this which i found whilst searching:

SELECT OrderID, OrderDate

FROM OrderTable

WHERE CustomerID = (SELECT CustomerID


need proper LINQ syntax #2


say now i wanna do this type of linq:

IEnumerable<MyStuff> r1 = from ....;

var rslt = from r2 ....
 join r1 ....
 where MyEval(r2.Field1, r1) ... <= #A

Func<Field1DataType, IEnumerable<MyStuff>, bool> <= #B

How do i code the #B ?

should I code it as a variable within the routine, or outside as a routine itself?


Any opinions on using Projection or explicit join syntax when joining entities in Linq to SQL?



I would like to know whether people use the join syntax OR projection when joining entities in LINQ to SQL queries. I have noticed that when using projection that a CROSS JOIN is in the generated SQL


var query =
from o in Orders
from  oi in o.OrderItems
where oi.OrderId == o.OrderId

generates SQL something like...

FROM [Customer].[Orders] AS [t0]
CROSS JOIN [Customer].[OrderItems] AS [t1]
WHERE ([t1].[OrderId] = [t0].[OrderId]) AND ([t1].[OrderId] = [t0].[OrderId])

whereas with explicit joins I get a clean inner join..

var query =
from o in Orders
join oi in OrderItems on o.OrderId equals oi.OrderId


FROM [Customer].[Orders] AS [t0]
INNER JOIN [Customer].[OrderItems] AS [t1] ON [t0].[OrderId] = [t1].[OrderId] 

I know using explicit joins over projection is frowned upon, but I am wary of those cross joins.

Just wondering what other folks preferences are when using joins in L2SQL.





Linq to SharePoint - connect to specific site collection


I have a site collection at http://[server]:[port]/sites/[name].  When I try to execute a linq query I get an exception saying that the web at http://[server]:[port]/sites/[name] cannot be found.  If I pass http://[server]:[port] to the datacontext that web is found, but the SPList I am trying to query cannot be found.

From looking online I know you cannot (without workarounds) query cross site collections, but I don't want to do that.  How do I connect to the specific site collection at http://[server]:[port]/sites/[name] with linq to sharepoint?

Need to add that I am using linq to sharepoint in an aspx web app that is running on the SharePoint server.

syntax to specify subobject collection as xaml resource


Sorry for the vague subject title.

A UserControl has an ObservableCollection

the UserControl is instantiated in MainWindow.xaml

I want to specify the collection defined within the usercontrol as a resource in MainWindow.xaml

I thought the syntax might be like the following


<local:myUserControl.MyCollection x:key="whatever"/>


However this produces an error "The attachable property 'MyCollection' was not found in type 'myUserControl'




Playing with Linq grouping: GroupByMany?

One of its features is grouping. Many people understand grouping like it is defined in Sql. Linq is implementing grouping quite the same way. Let's discover this syntax and how to make consecutive groups easier.

LINQ : Implementing IN and NOT IN

I got tried of typing

var result = from s in source
where items.Contains(s)
select s;and so I implemented the IN and NOT IN methods as extension methods:

101 LINQ Samples Tutorials

101 LINQ Example with sample code snippets....This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

Linq to Sql CompiledQuery container

Ok now let's go. Here is just a little trick but with some interesting patterns that could be useful in some other contexts not connected to Linq to Sql.

When using Linq expressions, like with Linq to Sql, translating the expression into something else (sql for example) is taking time and resources. Sometimes it's negligible, sometimes not...

LINQ to SQL Paging using GridView in C# and ASP.NET 3.5

This tutorial will show you how we can extend the LINQ to SQL Class and create methods that will allow us to page data from a SQL database. C# version.
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