Solved

LINQ Vs Hard Coding

Posted on 2011-09-29
4
216 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

623 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