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

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

if statements within Linq query?

Posted By:      Posted Date: October 05, 2010    Points: 0   Category :ASP.Net

Hi Guys,

I've got a query that on the face of it should be pretty simple, but I'm struggling.

I'm taking user input from a textbox, now if there's something in the textbox, that's fine, I can query against that, but what if there is nothing in there.

I'd like to be able to say if blank or NULL.

The logic I'm thinking of is:

if textbox is not blank then use contents of textbox
else search for blank or NULL 

I'm not quite sure how to implement this in a linq to sql structure of code.

I could simply have a different linq to sql code section depending on what the user has typed in, but I'm sure there must be a more sensible way, as the larger a form gets the more difficult it will be to achieve.

Any ideas are welcome.

View Complete Post

More Related Resource Links

Need help with a linq to sql query


I want to display some stats in a listview contril.  The table contains a record for every impression and for every click, and every record has a datetime field for the time and date of the impression of click.  I want to be able to display how many impressions and clicks there were in a given day and hour, something like below:

Date              Time                              Impressions    Clicks
8/20/2010                                               450              14            
                     Midnight -1:00am               150               5

Need Help in LINQ query for group By with chunks of record


I am assigning and unique id [strShipperIdSequence] on my List on bases of some properties which are grouped together uniquely.
Now what i needed is that my group should be further break down to some maximum amount of chunks.[Let say 10]
that mean's even i am having Same value in 12 records i should get 2 groups[I of 10 items and other of 2 items]

var uniqueGroups = objMdbContentInfoList.GroupBy(p => new
}).Select(g => g.First()).ToList();
foreach (var objUnique in uniqueGroups)
string strShipperIdSequence = APIGlobalMethods.GetShipperRequestID();
foreach (MdbContentInfo obj in objMdbContentInfoList.FindAll(h => (h.CON_ENTRY_POINT == objUnique.CON_ENTRY_POINT &&
h.APPTType == objUnique.APPTType &&

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

Basic Instincts: Increase LINQ Query Performance


Jared Parsons demonstrates a technique to achieve maximum performance from LINQ queries on large sets of data in order to create a responsive user interface.

Jared Parsons

MSDN Magazine August 2008

Data Points: Standard Query Operators with LINQ


LINQ to Objects and LINQ to Entities have an arsenal of Standard Query Operators that operate on sequences to perform a wide variety of operations.

John Papa

MSDN Magazine March 2008

Help with SQL query to Linq (VB.Net)



I am facing problems converting a relatively complex SQL query to a LinqToSQL statement. There are lots of examples on the web, but none involve 'joins' + 'where' + 'group'

Here is my query I am trying to use Linq for :

select Customers.CustomerID,          
       count(*) as NumOfOrders,         
       sum(Customers.BillingAmount) as BillingAmount,      
       sum(Orders.OrderTotal) as OrderTotal  
From Customers 
left outer join Orders on Customers.CustomerID = Orders.CustomerID
Where Customers.Name = @username	  
      and Customers.LastLoggedIn > @fromdate	  
      and Customers.LastLoggedIn < @throughdate	  
      and Customers.ZipCode = @zipcode 
group by Customers.CustomerID

I need help converting this to a LinqToSql for VB.Net

Thank you very much!

Linq query to DataTable


Is there option to convert from Linq.IQueryable to DataTable with some sort of CopyToDataTable() function. I am trying this.
     var row = from p in dc.ProductModels
                  select p;
    DataTable dt = row.CopyToDataTable();

Is there option to convert from Linq.IQueryable to DataTable with some sort of CopyToDataTable() function. I am trying this.

     var row = from p in dc.ProductModels


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 query with multiple joins, problem


I am using a LINQ query with multiple joins, the last join does not return any values even though values exist in the database. Below is my code.

when the query returns suiteNameTrg and SuiteTypeTrg are empty, all other values are returned correctly.

string suiteNameTrg = string.Empty;
            string suiteTypeTrg = string.Empty;
            using (DataClassesDataContext db = new DataClassesDataContext())
                    var productQuery = from assets in db.ASSETs
                    join relocatableUnits in db.RELOCATABLE_UNITs on assets.RUID equals relocatableUnits.RUID into assets_units
                    from relocatableUnits in assets_units.DefaultIfEmpty()
                   join build in db.BUILDINGs on assets.BUILDING_ID equals build.BUILDING_ID into assets_bins
                   from build in assets_bins.DefaultIfEmpty()
                   join test in db.TEST_SUITEs on assets.TEST_SUITE_ID equals test.TEST_SUITE_ID into test_bins
                   from test in test_bins.DefaultIfEmpty()
                    join testTrgt in db.TEST_SUITEs on assets.TARGET_TEST_SUITE_ID equals testTrgt.TEST_SUITE_ID into testTrgt_bins
                    from testTrgt in testTrgt_bins.DefaultIfEmpty()

                    select new

Dynamic Class with Linq query Result

Hi, var   query = db.Customers.Where( "City == @0 and Orders.Count >= @1", "London", 10). OrderBy( "CompanyName"). Select( "New(CompanyName as Name, Phone)");    I am using this query as a sample which returns a dynamicclass type, and i need this should to converted to a list collections or datatable etc., As i am holding it in my wcf service with linqtosql as dataaccesslayer. Trying to send the results to the UI which i have consumes this service. Kindly help me in this. Thanks query = db.Customers

How to write the LINQ query for the following

Hello All, I have an entity type with the following properties: UnitId, UnitDescription, ParentId, EffectiveDate - (Say the entitty type is Unit)  I want to filter out a list of UnitIds whose effective date is less than a given date. But since there could be many EffectiveDate s less than a given date, I want to take the latest one(Max). Simply told, I want to get the unit ids with the most recent effective date prior to a given date. How can I do this in a single linq statement? Appriciate any help.

Linq Query Union

HelloI need to use Union for below Linq queries. I could use Union it if it was simple "select new whith{" but Now that I Specified Class, I encounter Error using unionDim CStep() As New List(Of ProductModel) CStep= (From p In db.Produts _ Where p.CategoryID= 1 _ Select New ProductModel() With { _ .ID = p.ProductID, _ .Name = p.Title, _ } Take (5)).Union (From p In db.Produts _ Where p.CategoryID= 2 _ Select New ProductModel() With { _ .ID = p.ProductID, _ .Name = p.Title, _ } Take (5)).ToList()

Need to add hard coded values to LINQ query result

I am running a LINQ query which populates a list used by a DropDownList, I need to insert an "Unassigned" value to the list. The function below queries the values correctly from the db but does not insert the "Unaasinged" value to the list. Please help.   public List<KeyValuePair<int, string>> GetTestList() { KeyValuePair<int, string> item = new KeyValuePair<int, string>(0, "Unassigned"); using (DataClassesDataContext db = new DataClassesDataContext()) { var Query = from records in db.TEST_SUITEs orderby records.TEST_SUITE_ID select new KeyValuePair<int, string> ( records.TEST_SUITE_ID, string.Format(records.TEST_SUITE_ID + " " + records.SUITE_TYPE + " " + records.SUITE_NAME) ); //Query.ToList().Insert(0, item); Query.ToList().Insert(0,item); return Query.ToList(); } }  

Check if Linq query return result

HelloI have Linq query likeDim Prood= (From p InProdutcts _                                          where p.ProductID="InputInteger"                                                         ..... ) .SingleOrDefaultI could Use Count if I Use .ToList Instead of .SingleOrDefault , But now that I use 'SingleOrDefault', how Could I find if Prod contains any record or it's Empty.

Please help me to find out distinct value from linq to sql query given.

profileuserDataContext db = new profileuserDataContext(); var Q = (from p in db.edufinals join RM in db.edufinals on p.UserName equals RM.UserName where p.name.StartsWith(srcval) select new { p.name, RM.ProfielID, RM.ProfielPic, RM.city }).OrderBy(x => x.name).Distinct().Take(10);//, p.Key.ProfielID, p.Key.ProfielPic, p.Key.city, p.Key.country foreach (var pg in Q.Distinct()) { Response.Write(pg.name); ..................................... .................................... } how to refine this query to get distinct "name" column? Please help me to find out exact value.

Linq query in code behind

Hii would like to figure out this LinqDataSource in code-behind in vb.net<asp:LinqDataSource                 ID="lds" runat="server"                ContextTypeName="dbDataContext"                TableName="vKommentarUnion"                  Select="new(Key, Count() as Count, It as Items)" GroupBy="themen"                 where="isdrin=0"                AutoPage="true" AutoSort="true"            /> I found only samples in C#.How can i figure it out in vb?this does not run, what is wrong? Dim db As New dbDataContext Dim kommentare = From c In db.kommentar _ Group c By c.kursid Into Group _ Select key = c.kursid, count = Group.count, _ Items = From item In Group Select item lv.DataSource = k

Field method missing with LINQ query

H, I want to access the data from datatable object. When i trying to get the fieldslist usng "Field" method. But I could not find the method with my table object.  Eventhoguh i forcibly write a method and trying to access the fields, It is giving the below error for the first join in query. Rest of the lines are fine. What is the reason behind it. The errro: "Error 2 'LINQ2DB.SP_VS_OP' does not contain a definition for 'Field' and the best extension method overload 'System.Data.DataRowExtensions.Field<T>(System.Data.DataRow, string)' has some invalid arguments" What is the meaningof the error. Shall i do any other changes in the query line?                         var QueryChnl = from oSPOP in SPOP.AsEnumerable()                        join oDiscChannel in DiscChannel.AsEnumerable() on oSPOP.Field<int>("spid") equals oDiscChannel.Field<int>("SPID")                        join oChannel in Channel.AsEnumerable() on oDiscChannel.Field<in
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