none
Could it be done better in Linq

    Question

  • Hi

    I am looking for a better way to write this code. I need to do this:

    select the rows where Status= NA ,

    if not found

    select the rows where Status= Pending ,

    if not found

    select the rows where Status= Future,

    if not found

    select the rows where Status= Completed,

    Here is what I came up with :

    EnumerableRowCollection<DataRow> col= query.where (x=>x.Field<string>("Status")=="NA")
    if(col.count()==0)
    {
    col= query.where (x=>x.Field<string>("Status")=="Pending")
    if(col.count()==0)
    {
    col= query.where (x=>x.Field<string>("Status")=="Future")
    if(col.count()==0)
    {
    col= query.where (x=>x.Field<string>("Status")=="Completed")
    }
    }
    }

    Please let me know if this can be done in better way using Linq.

    Thanks

    Thursday, October 17, 2013 8:50 PM

Answers

  • Hello,

    Thanks for posting to this forum.

    With your code, it seems that you have used ADO.NET, if it is right?

    For achieving what you want with LinQ, I made a test and please have a look at it below:

    internal void Execute()
    
            {
    
                using (DataClasses1DataContext db = new DataClasses1DataContext())
    
                {
    
                    DateTime startTime = DateTime.Now;
    
                    List<StatusTable> col = db.StatusTables.Where(s => s.Status == "NA").ToList();
    
                    if (col.Count() == 0)
    
                    {
    
                        col = db.StatusTables.Where(s => s.Status == "Pending").ToList();
    
                        if (col.Count() == 0)
    
                        {
    
                            col = db.StatusTables.Where(s => s.Status == "Future").ToList();
    
                            if (col.Count() == 0)
    
                            {
    
                                col = db.StatusTables.Where(s => s.Status == "Completed").ToList();
    
                            }
    
                        }
    
                    }
    
                    DateTime endTime = DateTime.Now;
    
    
                    double costTime = (endTime - startTime).TotalSeconds;
    
    
                    Console.WriteLine("RowCount:" + col.Count() + "\ncostTime:" + costTime);
    
                }
    
            }
    

    The test result:

    We can see that even if we query more than 2000 records, it will take only 0.1 seconds.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, October 18, 2013 7:28 AM
    Moderator