domingo, 24 de agosto de 2014

C# Sort Dictionary

http://www.dotnetperls.com/sort-dictionary



C# Sort Dictionary

Sorted letters: A to Z



Dictionary has no Sort method. If we need to loop through the Dictionary contents in sorted order, we must separately acquire the elements and sort them. This is done with the Keys and Values properties and a List instance.

DictionaryList

Example

Dictionary



This example solves the problem by using the Keys property on the Dictionary instance. Then it uses the ToList extension method and the Sort instance method. An example Dictionary is created and populated with the Add method.



Next:The ToList and Sort methods are used on the Keys. The resulting List is looped through using the foreach-loop construct.

ToListForeach



Note:The var implicit typed keyword is used throughout to reduce syntactic redundancy.



Program that sorts keys in Dictionary: C#



using System;

using System.Collections.Generic;

using System.Linq;



class Program

{

    static void Main()

    {

// Create dictionary and add five keys and values.

var dictionary = new Dictionary<string, int>();

dictionary.Add("car", 2);

dictionary.Add("apple", 1);

dictionary.Add("zebra", 0);

dictionary.Add("mouse", 5);

dictionary.Add("year", 3);



// Acquire keys and sort them.

var list = dictionary.Keys.ToList();

list.Sort();



// Loop through keys.

foreach (var key in list)

{

   Console.WriteLine("{0}: {1}", key, dictionary[key]);

}

    }

}



Output



apple: 1

car: 2

mouse: 5

year: 3

zebra: 0



Example 2

KeyValuePair: Key and Value properties



Next we show how to sort the values in a Dictionary. This program adds keys to a Dictionary and then sorts them by their values. Dictionary instances are not initially sorted in any way. We use the orderby keyword in a query statement.

OrderBy Clause



Program that sorts Dictionary: C#



using System;

using System.Collections.Generic;

using System.Linq;



class Program

{

    static void Main()

    {

// Example dictionary.

var dictionary = new Dictionary<string, int>(5);

dictionary.Add("cat", 1);

dictionary.Add("dog", 0);

dictionary.Add("mouse", 5);

dictionary.Add("eel", 3);

dictionary.Add("programmer", 2);



// Order by values.

// ... Use LINQ to specify sorting by value.

var items = from pair in dictionary

   orderby pair.Value ascending

   select pair;



// Display results.

foreach (KeyValuePair<string, int> pair in items)

{

   Console.WriteLine("{0}: {1}", pair.Key, pair.Value);

}



// Reverse sort.

// ... Can be looped over in the same way as above.

items = from pair in dictionary

orderby pair.Value descending

select pair;

    }

}



Output



dog: 0

cat: 1

programmer: 2

eel: 3

mouse: 5



Steps



First, it declares an example Dictionary. It contains keys in an arbitrary order. The Dictionary keys are strings. Its values are ints. We will reorder the values to go from lowest to highest.



It uses a LINQ query with the var keyword and accesses the KeyValuePairs from the Dictionary. It finally displays results, using foreach to iterate through and display each KeyValuePair. No additional lookups are required.

LINQVarKeyValuePair



Note:Thanks to Jon Senchyna for improving the query expression. It is more efficient to use the collection of KeyValuePairs.

OrderBy

Lambda expression syntax



Another option is the OrderBy extension method in System.Linq. This approach compiles to the same code as the orderby query expression. But the syntax is shorter. It requires only one lambda expression and method call.

Lambda



Program that uses OrderBy method: C#



using System;

using System.Collections.Generic;

using System.Linq;



class Program

{

    static void Main()

    {

var items = new Dictionary<int, int>();

items.Add(-1, 0);

items.Add(0, 1);

items.Add(-2, 0);

items.Add(3, 1);



// Use OrderBy method.

foreach (var item in items.OrderBy(i => i.Key))

{

   Console.WriteLine(item);

}

    }

}



Output



[-2, 0]

[-1, 0]

[0, 1]

[3, 1]



Note:Thanks to Even Holen for writing in with an example of the shorter OrderBy syntax form.

Discussion

Warning: exclamation mark



You will likely add more logic to the solution here for your project.

The above console program could,

with certain changes,

raise a KeyNotFoundException. You will want to trap those errors with exception handling\u2014try and catch.

TryCatch



It is possible and easy to sort in the opposite direction. Simply replace the keyword ascending with descending. When you omit the direction keyword entirely, it will use ascending. You can find more information on descending.

Descending



Descending sort



var items = from pair in dictionary

   orderby pair.Value descending

   select pair;



Example output



mouse: 5

eel: 3

programmer: 2

cat: 1

dog: 0



Question and answer



Other methods I found involve more steps, more lines of code, or delegates and anonymous functions. There is nothing wrong with those methods, although they vary in efficiency. You may prefer this sort of home-grown solution.



Sort string values. Sorting strings would work just as well. What the runtime is doing is using the interface implementations of the types. Its syntax is the same for any type that List.Sort() could sort.

IComparable

Summary



As a hashtable, Dictionary is optimized for fast lookups, not for specific looping mechanisms. So while Dictionary is invaluable for lookup-heavy programs, it hinders programs that demand certain enumeration patterns\u2014such as sorted keys.



C#: Sort


What's a busness object

http://docs.imis.com/15.2.0/index.htm?turl=whatisabusinessobject2.htm



What is a business Object?

A general definition, from the Object Management Group:
A business object is a representation of a thing active in the business domain, including at least its business name and definition, attributes, behavior, relationships and constraints. A business object may represent, for example, a person, place or concept. The representation may be in a natural language, a modeling language, or a programming language.
An iMIS-specific definition, in terms of the Business Object Designer:
A business object is an iMIS system construct representing the data elements and business rules of a business concept like a contact; it is implemented using a combination of business rules, a schema definition that describes the data structures of the object’s properties, and a database view.
Elements of a Business Object
These are the basic elements of an iMIS business object.
■    Properties – attributes of the object (typically map to database columns). For example, Contact.LastName
■    Property constraints – logic that is executed whenever a property value changes. If constraint logic fails, the property value is not changed.  For example, LastName cannot be blank
■    Object constraints – logic that is executed whenever an object is created, modified, or deleted. If constraint logic fails, the attempted action is not committed. For example, If the contact gender is female, then the prefix cannot be Mr.
■    Actions – logic that is executed whenever an object is created, modified, or deleted. Actions do not pass or fail (unlike constraints), they just run. For example, When a company contact is set to inactive, set all company employees to inactive


■    Branches – used to provide inheritance-like functionality for similar objects – i.e., objects similar enough to be represented within a single object definition.