Solved

Help with LINQ order by query syntax

Posted on 2014-10-14
10
126 Views
Last Modified: 2016-02-15
Hi, the following code works fine

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication198
{
    class Test
    {
        public String Name { get; set; }
        public int ID { get; set; }
    }

    class Program
    {
        public void Start()
        {
            Test t1 = new Test{Name = "Fred", ID = 123 };
            Test t2 = new Test { Name = "John", ID = 4 };
            List<Test> t = new List<Test> { t1, t2 };

            var p = (new String[] { "All Employees" }).Union(from x
                                                                in t
                                                                orderby x.Name ascending
                                                                  select x.Name                                                                 
                                                            ).ToList<String>();
            //p is a List<String> that I can assign to a dropdownList.DataSource
            //and "All Employees" appears at the top, most of the time
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Start();
        }
    }
}

Open in new window


It works.
"p" is used as a DataSource for a DropDownList
All of the time in this test program things always work.
Most but not all the time it works in a more complex program. The problem I am seeing is that "All Employees" in my real application only sometimes appears at the top of the list. I always need it at the top of the list in my drop down.

Can someone help how I can "order by" to ensure that "p" is always a list where p[0]="All Employees".

Thank you
0
Comment
Question by:John Bolter
  • 4
  • 3
  • 2
10 Comments
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 250 total points
ID: 40380116
Hi John;

I have removed the method call to Union and placed an Insert method call to insert  "All Employees" at the beginning of the List.

var p = (from x in t
         orderby x.Name ascending
         select x.Name
         ).ToList<String>();

// Insert this value at the begining of the list.
p.Insert(0, "All Employees");

Open in new window

0
 
LVL 33

Assisted Solution

by:it_saige
it_saige earned 250 total points
ID: 40380273
I agree with Fernando.

You either insert the "All Employees" item to the list at the 0 position:
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication198
{
	class Test
	{
		public String Name { get; set; }
		public int ID { get; set; }
	}

	class Program
	{
		public void Start()
		{
			Test t1 = new Test { Name = "Fred", ID = 123 };
			Test t2 = new Test { Name = "John", ID = 4 };
			List<Test> t = new List<Test> { t1, t2 };
			List<String> p = new List<String>();

			p = (from x in t
				orderby x.Name ascending
				select x.Name).ToList();
			//p is a List<String> that I can assign to a dropdownList.DataSource
			//and "All Employees" appears at the top, most of the time

			p.Insert(0, "All Employees");

			foreach (var employee in p)
				Console.WriteLine(employee);
			Console.ReadLine();
		}

		static void Main(string[] args)
		{
			Program p = new Program();
			p.Start();
		}
	}
}

Open in new window

Output:Capture.JPGOr create the list with the first item specified as "All Employees" and then use List.AddRange(IEnumerable<String>) to add your remaining elements:
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication198
{
	class Test
	{
		public String Name { get; set; }
		public int ID { get; set; }
	}

	class Program
	{
		public void Start()
		{
			Test t1 = new Test { Name = "Fred", ID = 123 };
			Test t2 = new Test { Name = "John", ID = 4 };
			List<Test> t = new List<Test> { t1, t2 };
			List<String> p = new List<String>() { "All Employees" };
			p.AddRange(from x in t
					 orderby x.Name ascending
					 select x.Name);
			//p is a List<String> that I can assign to a dropdownList.DataSource
			//and "All Employees" appears at the top, most of the time

			foreach (var employee in p)
				Console.WriteLine(employee);
			Console.ReadLine();
		}

		static void Main(string[] args)
		{
			Program p = new Program();
			p.Start();
		}
	}
}

Open in new window

Output:Capture.JPG
-saige-
0
 

Author Comment

by:John Bolter
ID: 40380285
I was so close.
Thank you both
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40380291
@John, while I appreciate the points.  I really think that Fernando deserves credit also.

-saige-
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:John Bolter
ID: 40380297
I tried to split it 50:50 but I couldn't figure out how. And now I can't seem to undo it. I thought it too.
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40380302
We can have an administrator reopen so that you can re-assign the points accordingly.

-saige-
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40380304
I have sent an attention request.

-saige-
0
 

Author Comment

by:John Bolter
ID: 40380318
Thanks & sorry about this guys, 50/50, it was my error.
I can't see to write LINQ or use this website :-(
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 40380553
Thank you -saige- and John for your efforts.
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

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

896 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

12 Experts available now in Live!

Get 1:1 Help Now