Solved

LINQ Vs Hard Coding

Posted on 2011-09-29
4
212 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

733 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