.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

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

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

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")


View Complete Post

More Related Resource Links

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


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.


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

Conversion of List to DataTable and ViceVersa


hi ,

           Iam having a requirement where I wil get datatable or Dataview from the DataAccessLayer I need to convert them into GanaricList of entites and ViceVersa from GenericList to Datatable or DataView.

             I tried it but I cant. Can anybody help me out.

linq and max, if return null return error


hi there
i have this query :

var result2 = (from TH in DB.Threshold
                          where TH.ProductSKUID == int.Parse(HID_ProductSKUID.Value)
                          select TH.ThresholdID).Max();

the problem is that if this query does not find any items, return null, so thow exception
how can i do to return 0??

Linq to SQL returns null for DateTime fields.


I have a linq to sql entity class in which I declared some DateTime fileds like this:

[Column(DbType = "smalldatetime")]
public DateTime? StartDate { get; set; }

And this is how I fetch data form repository:

return repository.Logs.OrderByDescending(l => l.LogID).FirstOrDefault();

All non DateTime fields are filled properly but all datetimes are null.

[Column(DbType = "smalldatetime")]

        public DateTime? StartDate { get; set; }

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)

Updating a List item field value in a SPD Workflow is setting Date fields to null

Hello everybody,I faced a very weird behavior while creating a workflow in SPD against a Document Library.Here is the case:1- Create a document library in sharepoint site.2- Add a custom column of type DATE.3- Upload any document to the library4- Edit the item metadata and set the custom date field to any date you want.5- Now using sharepoint designer, create a very simple Workflow with only one action that updates the current item "Title" field to any value. (Note: In my case I set the workflow to start manually and not automatically)6- Save the workflow and then start it on the uploaded item.7- Now check the value of the date column after the workflow is finished.8- You will see that the Date field is Empty... (very weird)Notes:   1-This behavior will not appear on a standard list. it is only appearing in a Document library.  2- I am using WSS 3.0 SP2 + MOSS 2007 SP2. Also SharePoint designer 2007 SP2Did anyone face this situation and does it have a fix, or am I doing something wrong here... Please help.Regards,Maheed

How to generate List Menu form the DataTable

Hi all,This is my c# code.public partial class HorizontalCssMenu : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            LoadMenu();        }    }    private void LoadMenu()    {        DataTable dtMenu = LoadData();        StringBuilder sb = new StringBuilder();        foreach (DataRow dr in dtMenu.Rows)        {            if (string.IsNullOrEmpty(Convert.ToString(dr["ParentID"]))                || Convert.ToString(dr["ParentID"]) == "0")            {                sb.AppendLine("<ul>");                sb.AppendLine("<li ID=\"" + Convert.ToString

how to in Insert database NULL if drop down list item is not selected ?

hi,   on my aspx I have the below DDL   <asp:DropDownList ID="ColorDDL" runat="server" DataSourceID="ColorObj"                                                 DataTextField="Size" DataValueField="BustId" Width="150px"                                                 AppendDataBoundItems="True">                                                    <asp:ListItem Value="-1">(Optional)</asp:ListItem>                             &n

delete a row in datatable using linq to dataset

hihow can i delete a row in datatable using linq to dataset?I have a dataset in my project, need to delete some rows filtered by IDhow can i do?

Converting Date to String and Formating it Linq to SQL

Hello I have problem in converting date to string I am using cstr(p.tripstart) , which is returning Date as 12 Aug 2010 12:AM   I need to make formating   This is my code : Dim db As New TripsLinqDataContext Dim listtrips = (From p In db.Trips _ Group Join c In db.Countries On p.TripCountryID Equals c.TripCountryID Into countrylist = Group _ Select New With {.Tripdetails = p.TripDescription + " - " + p.TripCityList + " - " + CStr(p.tripstart) + " - " + CStr(p.TripDays), _ .Tripid = p.TripID}).ToList tripboxlist.DataSource = listtrips tripboxlist.DataTextField = "Tripdetails" tripboxlist.DataValueField = "Tripid" tripboxlist.DataBind()     Regards  

Linq null value

 Hello,I am making a website to store invoices so i can mail them to clients. So i got a table for clients, invoices and one with invoice products/services. When an invoice has no products/services added to them and it returns null i get the error "the null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type."I just started with linq. Before i always used mysql. Mostly i just had to call data from 1 table so forgive me if my linq query isn't really correct.  Dim invoices = From i In db.invoices _                       Group Join p In db.products On i.id Equals p.invoiceId Into invoiceProducts = Group _                       Select New With {i.client.naam, i.titel, (From iP In invoiceProducts Select iP.prijs).Sum} So the idea is that i show the client's naam, the title of the invoice and the total amount the clients will need to pay for products and services. Kind regards Geert

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"]);

ImageList and a system image list handle

How can I have an ImageList use an image list handle of a systems image list, such as one that can be returned from SHGetFileInfo ? My image list is associated with a ListView control and this could be easily done in Win32 through the LVM_SETIMAGELIST message with an image list handle but I see no easy way of doing this with the .Net System.Windows.Forms.ImageList component.

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

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
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