Solved

LINQ Vs Hard Coding

Posted on 2011-09-29
4
209 Views
Last Modified: 2013-12-17
Experts,

I`m using LINQ to retrieve some objects based on some property. Everything works great. I was wondering if there was a different way of doing it. Lets say in C# code.
What would be my algorithm be? Do I have to go through each element individually, check the property? Basically I want to look for a property and then order them according to a different property.

In the example, I get a sublist based on Tag, order it by Time.

Here is what I`m doing in LINQ. Code examples would be really helpful.


SubList = (from Obj in MainList
                                  orderby Obj.Time
                                  where Obj.IDTag == Tag
                                  select Obj).ToList();

Open in new window

0
Comment
Question by:San24
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 36818050
Here is one approach.
using System;
using System.Collections.Generic;

namespace _27362379
{
    class Program
    {
        static void Main(string[] args)
        {
            int Tag = 1;                                    // Tag to search for
            List<SomeObj> MainList = new List<SomeObj>()    // Simulate existing data
            {
                new SomeObj() { IDTag = 1, Time = DateTime.Now },
                new SomeObj() { IDTag = 2, Time = DateTime.Now.AddHours(1) },
                new SomeObj() { IDTag = 3, Time = DateTime.Now.AddHours(3) },
                new SomeObj() { IDTag = 1, Time = DateTime.Now.AddHours(2) },
                new SomeObj() { IDTag = 2, Time = DateTime.Now.AddHours(6) },
                new SomeObj() { IDTag = 3, Time = DateTime.Now.AddHours(7) },
            };

            List<SomeObj> results = new List<SomeObj>();    // Result of search

            foreach (SomeObj Obj in MainList)
            {
                if (Obj.IDTag == Tag)
                {
                    results.Add(Obj);
                }
            }

            results.Sort(new SomeObjTimeComparer());        // Sort by time using the Comparer
        }
    }


    /// <summary>
    /// Implements the IComparer interface. This class will be passed as an argument to List.Sort
    /// and it will sort based on comparing the Time values of each object in the List.
    /// </summary>
    public class SomeObjTimeComparer : IComparer<SomeObj>
    {
        #region IComparer<SomeObj> Members

        public int Compare(SomeObj x, SomeObj y)
        {
            return x.Time.CompareTo(y.Time);
        }

        #endregion
    }

    /// <summary>
    /// A sample class.
    /// </summary>
    public class SomeObj
    {
        public int IDTag { get; set; }
        public DateTime Time { get; set; }
    }
}

Open in new window

0
 

Author Comment

by:San24
ID: 36818119
@Kaufmed : Let me implement this in my code and see if I see any performance gains. I`m actually thinking of changing the structure of my classes itself, so that I don`t have to do LookUps and Sorting.

Let me keep you posted.
0
 
LVL 2

Assisted Solution

by:yogsoft
yogsoft earned 250 total points
ID: 36895658
There is another alternative for LINQ (i. .e method chaining with extension methods). Check below example.

 
var mainList = new Dictionary<string, string>();
           
            mainList.Add("Yogesh", "SomeString");
            mainList.Add("Nitin", "Deshmukh");
            mainList.Add("Ashok", "SomeString");
                        
            var SubList = mainList.Where(ml => ml.Value == "SomeString").OrderBy(ml1 => ml1.Key).ToList();

Open in new window

0
 

Author Comment

by:San24
ID: 36903897
@Kaufmed :

Can I use the sort this way?

Then I could just do a results.Sort();

For some reason this doesn`t seem to work.


#region IComparable<SomeObj> Members

        int IComparable<Trajectory>.CompareTo(SomeObj Other)
        {
            return Other.Time.CompareTo(Time);
        }

        #endregion

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

937 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now