Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

LINQ Vs Hard Coding

Posted on 2011-09-29
4
Medium Priority
?
219 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 1000 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 1000 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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

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…
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…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
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…

715 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