Solved

LINQ Vs Hard Coding

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

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

707 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

18 Experts available now in Live!

Get 1:1 Help Now