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.

terça-feira, 13 de maio de 2014

Object Swapping Part 1: Its Surprising Importance | Dr Dobb's

Object Swapping Part 1: Its Surprising Importance | Dr Dobb's



Object Swapping Part 1: Its Surprising Importance

March 14, 2012
If you're like most C++ programmers, you probably learned about copy constructors and copy-assignment operators as part of learning how to define your own classes; and not until much later — if at all — did you learn about how to define a useful swap operation for your class. I am beginning to believe that this strategy is a mistake — that swapping is as fundamental an operation as copying, and that it may even be more fundamental than assignment.
To see why, let's start by considering an analogous pair of operations: + and +=. If we are defining a class T, the naïve approach is to define + first, and then define += in terms of it:
1
2
3
4
5
6
7
8
9
10
11
12
     // Naïve
class T {
     public:
           // …
           friend T operator+(const T&, const T&);
  
           // += defined in terms of +
           T& operator+=(const T& t) {
                *this = *this + t;
                return *this;
           }
     };
The precise definition of operator+ doesn't matter here; what matters is that operator+creates a new object of type T that depends in some way on the contents of its two arguments.
There's nothing outright wrong with this strategy, but it has a drawback: Every time we execute +=, we create a new object, assign that object to the left-hand side of +=, and then throw it away. This extra object gets created and destroyed even if there is a way to do the computation implied by += without that object. By definition, + has to create a new object, but += doesn't — so the way to solve this problem is to turn it around and define + in terms of +=:
1
2
3
4
5
6
7
8
9
10
11
12
13
     // Less naïve
class T {
     public:
           // …
           T& operator+=(const T& t);
     };
  
     // + defined in terms of +=
T operator+(const T& a, const T& b) {
           T result = a;
          result += b;
           return result;
     }
Here I have omitted the definition of +=, just as earlier I omitted the definition of +. By refactoring the code in this way, I have caused += to do just the essential work, and then wrapped += in a function that constructs a new object, uses += to augment that object, and then returns the object.
Similar, but less obvious, reasoning applies to the relationship between copying, swapping, and assignment. If we want to implement swapping in terms of copying and assignment, we might do so this way:
1
2
3
4
5
6
7
8
9
10
             // Naïve
class T {
     public:
           // …
           // Swap defined in terms of copy and assignment
           void swap(T& t) {
                T temp = t;
                t = *this;
                *this = temp;
           };
     };
Alternatively, if we have copying and swapping available to us, we can implement assignment this way:
1
2
3
4
5
6
7
8
9
             // Less naïve
class T {
     public:
           // …
           // Assignment defined in terms of copy and swap
           T& operator=(const T& t) {
                T temp = t;
                this->swap(temp);
                return *this;
           }
     };
Here, the statement
1
T temp = t;
is, of course, a copy-initialization, not an assignment; so there is no recursion loop.
It has taken me a long time to realize that this second approach is superior to the first in virtually every way except its subtlety. For example, it is a generally desirable property of operations that might throw an exception that they complete either all of the requested operation or none of it. This definition of operator= does not have that property, for if the statement
1
*this = temp;
in the first example throws an exception, the value of t has already been overwritten. As a result, the swap operation has changed one but not both of its operands before throwing an exception — even if assignment and copy have the desirable property of doing everything or nothing. In contrast, if swapping has the all-or-nothing property, then so does the operator=that we have defined in terms of it.
As another example, for many data structures it is possible to define swapping in a way that is much faster than copying or assignment, because swapping normally does not require replicating the data in the data structure. Therefore, defining swapping in terms of copying and assignment has the potential of wasting enormous amounts of time, whereas defining assignment in terms of copying and swapping avoids that waste.
The fundamental point is that like +, assignment combines operations. In the case of +, there were two operations, namely creating a new object and combining a second object with it. In the case of assignment, there were three operations: creating a copy of the right-hand side, destroying the old value of the left-hand side, and storing the copy as the new value of the left-hand side.
In both cases, we are better off implementing the operations separately and combining them as needed. In the case of +, we constructed a temporary object and used += to combine it with another; in the case of assignment, we used the copy constructor to construct a temporary object as a copy of the right-hand side, swapped that copy with the left-hand side, and finally let the temporary object's destructor get rid of it.
Next week, I'll show how swapping instead of assigning can make some algorithms dramatically faster.