Vous êtes sur la page 1sur 32

http://www.aspfree.

com/c/a/C-Sharp/Building-Csharp-Comparable-Objects-IComparable-versusIComparer/
Saravana Arivazhagan 10:36 AM

http://en.csharp-online.net/Should_I_use_an_abstract_class_or_an_interface%3F

C# Array.BinarySearch Method
Program that uses Array.BinarySearch method [C#]
Object 1

using System; class Program { static void Main() { // // Source array that is ordered ascending. // string[] array = { "a", "e", "m", "n", "x", "z" }; // // Call versions of the BinarySearch method. // int index1 = Array.BinarySearch(array, "m"); int index2 = Array.BinarySearch<string>(array, "x"); int index3 = Array.BinarySearch<string>(array, "E", StringComparer.OrdinalIgnoreCase); // // Write results. // Console.WriteLine(index1); Console.WriteLine(index2); Console.WriteLine(index3); } } Output 2 4 1

Inserting Items into a C# List


The Insert() method is provided for this specific purpose. Insert() takes two arguments, an integer indicating the index location of the insertion and the item to be inserted at that location. For example, to insert an item at location 2 in our example list:
colorList.Insert(2, "White");

Finding Items in a C# List or ArrayList


he most basic method is the Contains() method, which when called on a List or ArrayList object returns true if the specified item is found in the list, or false if it is not. The IndexOf() method returns the index value of a matching item in a list. For example, the following code sample will output the value 2, which is the index position of the "Yellow" string:
List<string> colorList = new List<string>(); colorList.Add colorList.Add colorList.Add colorList.Add colorList.Add ("Red"); ("Green"); ("Yellow"); ("Purple"); ("Orange");

Console.WriteLine(colorList.IndexOf("Yellow"));

If the item is not found in the List a value of -1 is returned by the IndexOf() method. This technique could be used to replace a specific value with another. For example, without knowing in advance the index value of the "Yellow" string we can change to "Black":
colorList[colorList.IndexOf("Yellow")] = "Black";

The LastIndexOf() method returns the index value of the last item in the list to match the specified item. This is particularly useful when a list contains duplicate items.

C# List Examples
Arrays do not resize dynamically. The List type in the C# language does. With List, you do not need to manage the size on your own. Lists are dynamic arrays in the C# language. They can grow as needed when you add elements. CAPACITY: Gets or sets the total number of elements the internal data structure can hold without resizing.

C# BinarySearch List
Program that uses BinarySearch [C#] using System; using System.Collections.Generic; class Program { static void Main() { List<string> l = new l.Add("acorn"); l.Add("apple"); l.Add("banana"); l.Add("cantaloupe"); l.Add("lettuce"); l.Add("onion"); l.Add("peach"); l.Add("pepper"); l.Add("squash"); l.Add("tangerine");

List<string>(); // 0 // 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8 // 9

// This returns the index of "peach". int i = l.BinarySearch("peach"); Console.WriteLine(i); // This returns the index of "banana". i = l.BinarySearch("banana"); Console.WriteLine(i); // This returns the index of "apple". i = l.BinarySearch("apple"); Console.WriteLine(i);

} } Output 6 2

Description. Three values are looked up. The locations of "peach", "banana", and "apple" are looked up in the List. Note that the List is in alphabetical order. BinarySearch won't work if your List or array is not already sorted. It doesn't matter if you use numeric, alphanumeric, or ASCII sorting.

Benchmark

I found here that binary search becomes more efficient in comparison to a linear search with large collections. For small collections of less than about 100 elements, BinarySearch is slower, probably due to implementation overhead.

C# List CopyTo Method


Program that uses CopyTo on List [C#] using System; using System.Collections.Generic; class Program { static void Main() { // Create a list with three elements. var list = new List<int>() { 5, 6, 7 }; // Create an array with length of three. int[] array = new int[list.Count]; // Copy the list to the array. list.CopyTo(array); // Display. Console.WriteLine(array[0]); Console.WriteLine(array[1]); Console.WriteLine(array[2]); } }

Output 5 6 7

Get range of elements


Here we see how you can get a range of elements in your List collection using the GetRange instance method. This is similar to the Take and Skip methods from LINQ, but has different syntax.
Program that gets ranges from List [C#] using System; using System.Collections.Generic; class Program { static void Main() { List<string> rivers = new List<string>(new string[] { "nile", "amazon", // River 2 "yangtze", // River 3 "mississippi", "yellow" }); // Get rivers 2 through 3 List<string> range = rivers.GetRange(1, 2); foreach (string river in range) { Console.WriteLine(river); } } }

Output amazon yangtze

Var
Lists can also be created by using var keyword Here we see how you can use List collections with the var keyword. This can greatly shorten your lines of code, which sometimes improves readability. The var keyword has no effect on performance, only readability for programmers.
Program that uses var with List [C#] using System.Collections.Generic; class Program { static void Main() { var list1 = new List<int>(); // <- var keyword used List<int> list2 = new List<int>(); // <- Is equivalent to }

C# : Difference between Array and Arraylist


System.Array 1 Arrays are strongly typed. System.Collections.ArrayList An arraylist is NOT strongly typed.

That is all the elements have to be of the same type. You can have a combination of built For example an array of integers has to have all in types (int,string etc) in your integers. It cannot have a mix of integers and strings. arraylist. 2 Cannot be dynamically resized. (Note :Array.Resize() doesnot actually resize the existing array. It infact creates a new array with the required length and copies values from the old array to new array. Using the Resize is more memory intensive than AddRange() in arraylist) 3. Eg int[] myIntArray = new int[2] myIntArray[0]=10; myIntArray[1]=20; Eg ArrayList leaderNames = new ArrayList(); leaderNames.Add("Obama"); leaderNames.Add(5); Can be dynamically resized using the method Arraylist.AddRange()

ArrayLists
You use an ArrayList when your collection may need items adding to it, deleting from it, or needs sorting. For example, suppose you are teacher with a class of ten children. You could keep a list of the children's names, add new students, delete ones who leave, and even sort them into brightest and dimmest! If you used a normal array, it would be difficult to do these things. ArrayList students = new ArrayList(); students.Add("Jenny"); students.Add("Peter"); students.Add("Mary Jane");
//Array List integer ArrayList students = new ArrayList(); students.Add(1); students.Add(2); students.Add(3); foreach (int p in students) Console.WriteLine(p); //Array List string ArrayList students1 = new ArrayList();

students1.Add("wew"); students1.Add("aew"); students1.Add("qqq"); students1.Add("bbb"); students1.Add("yyyy"); // Removing elements form array list students1.Remove("qqq"); //Array list sorting students1.Sort(); foreach (string p in students1) Console.WriteLine(p); Console.WriteLine("After removal"); // 0 is index and 2 is total count students1.RemoveRange(0, 2); foreach (string p in students1) Console.WriteLine(p);

Output: aew bbb yyyy wew After removal yyyy wew How to Insert an Item in an ArrayList ? Syntax : ArrayList.insert(index,object) index : The position of the item in an ArrayList object : The Item to be add the ArrayList ArrayList arr; arr.Insert(3, "Item3"); How to remove an item in a specified position from an ArrayList ? Syntax : ArrayList.RemoveAt(index) index : the position of an item to remove from an ArrayList ItemList.RemoveAt(2) How to sort ArrayList ? Syntax : ArrayList.Sort()

ArrayList method example


Structural programming with ArrayList is easy, as you can simply pass the object with the ArrayList type. However, in the receiving function, you have to know (or find out) what the type of each element is. Here

we pass the ArrayList as an argument.


Program that uses ArrayList parameter [C#] using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList and add two ints. // ArrayList list = new ArrayList(); list.Add(5); list.Add(7); // // Use ArrayList with method. // Example(list); } static void Example(ArrayList list) { foreach (int i in list) { Console.WriteLine(i); } } } Output 5 7

Combine example
There are different ways to add one ArrayList to another, but the best way is using AddRange. Internally, AddRange uses the Array.Copy or CopyTo methods, which have better performance than some loops.
Program that uses Add and AddRange [C#] using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with two values. // ArrayList list = new ArrayList(); list.Add(5); list.Add(7); //

// Second ArrayList. // ArrayList list2 = new ArrayList(); list2.Add(10); list2.Add(13); // // Add second ArrayList to first. // list.AddRange(list2); // // Display the values. // foreach (int i in list) { Console.WriteLine(i); } } }

Output 5 7 10 13

ArrayList Sort and Reverse


ArrayList list = new ArrayList(); list.Add("Cat"); list.Add("Zebra"); list.Add("Dog"); list.Add("Cow"); // // Sort the ArrayList. // list.Sort(); // // Display the ArrayList elements. // foreach (string value in list) { Console.WriteLine(value); } // // Reverse the ArrayList. // list.Reverse(); // // Display the ArrayList elements again. // foreach (string value in list) { Console.WriteLine(value); } } }

Insert and remove elements


ArrayList list = new ArrayList(); list.Add("Dot"); list.Add("Net"); list.Add("Perls"); // // Remove middle element in ArrayList. // list.RemoveAt(1); // It becomes [Dot, Perls] // // Insert word at beginning of ArrayList. // list.Insert(0, "Carrot"); // It becomes [Carrot, Dot, Perls] // // Remove first two words from ArrayList. // list.RemoveRange(0, 2); // // Display the result ArrayList. // foreach (string value in list) { Console.WriteLine(value); // <-- "Perls" } } }

Get range of values


Another interesting method you can use is the GetRange method, which will return to you a subset of the original ArrayList in a new ArrayList. This is ideal when you know a certain part of your ArrayList has a different purpose or behavior.
Program that uses GetRange [C#] using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with 4 strings. // ArrayList list = new ArrayList(); list.Add("fish"); list.Add("amphibian"); list.Add("bird"); list.Add("plant"); // // Get last two elements in ArrayList. // ArrayList range = list.GetRange(2, 2); // // Display the elements.

} } Output bird plant

// foreach (string value in range) { Console.WriteLine(value); // bird, plant }

Hashtable : A Hashtable is a type of collection where each item is made up of a "Key and Value" pair. It's most commonly used in situations where you want to be able to do a quick look-up based on a certain single value. The piece of information that you use to perform the look-up is the 'key', and the object that is returned is the "Value". Hashtables are designed for situations where you want to be able to quickly pick out a certain item from your collection, using some unique identifying key - similar to the way you might select a record from a database using an index, or the way you might pick out the contact details of a person using their name as the 'unique identifier'. You use an Hashtable when you want to store information based on Key/Value pairs. For example, the name of a student AND the score in an exam. This allows you to mix text and numbers. Hashtable students = new Hashtable(); students["Jenny"] = 87; students["Peter"] = "No Score"; students["Mary Jane"] = 64; students["Azhar"] = 79; Or like this: students.Add("Jenny", 87); students.Add("Peter", "No Score";); students.Add("Mary Jane", 64); students.Add("Azhar", 79); students["Jenny"] = 87;

key value The second way to store values in an Hashtable is to use the Add Method: students.Add("Jenny", 87); In between the round brackets of Add( ), you first type the Key name. After a comma, you type the Value

for that Key. There is a difference between the two. If you use the Add method, you can't have duplicate Key names. But you can if you use the square brackets. So this will get you an error: students.Add("Jenny", 87); students.Add("Jenny", 35); But this won't: students["Jenny"] = 87; students["Jenny"] = 35; DictionaryEntry child This sets up a variable called child. But note the type of variable it is: a DictionaryEntry. C# uses an object of this type when using the foreach loop with Hashtables. That's because it automatically returns both the Key and the Value.
Hashtable ht = new Hashtable(); ht.Add("ad", 1); foreach (DictionaryEntry aaa in ht) Console.WriteLine("name=" + aaa.Key + "value=" + aaa.Value); OUTPUT:

name=ad value=1
ht.Remove("ad"); Console.WriteLine("After Removal"); foreach (DictionaryEntry aaa in ht) Console.WriteLine("name=" + aaa.Key + "value=" + aaa.Value);

ContainsKey : Check if a specified key exist or not Synatx : bool HashTable.ContainsKey(key) Key : The Key value for search in HahTable Returns : return true if item exist else false ht.Contains("1"); ContainsValue : Check the specified Value exist in HashTable Synatx : bool HashTable.ContainsValue(Value) Value : Search the specified Value in HashTable Returns : return true if item exist else false ht.ContainsValue("Sunday") DICTIONARY: Dictionary provides fast lookup of elements. It is used when you have many different elements. It is found in the System.Collections.Generic namespace.
using System; using System.Collections.Generic; class Program

static void Main() { Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("cat", 2); dictionary.Add("dog", 1); dictionary.Add("llama", 0); dictionary.Add("iguana", -1); }

check to see if a given string is present

using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("apple", 1); dictionary.Add("windows", 5); // See whether Dictionary contains this string. if (dictionary.ContainsKey("apple")) { int value = dictionary["apple"]; Console.WriteLine(value); } // See whether Dictionary contains this string. if (!dictionary.ContainsKey("acorn")) { Console.WriteLine(false); } } }

Output 1 False Program that uses foreach on Dictionary [C#] using System; using System.Collections.Generic; class Program { static void Main() { // Example Dictionary again Dictionary<string, int> d = new Dictionary<string, int>() { {"cat", 2}, {"dog", 1}, {"llama", 0}, {"iguana", -1}

} } Output

}; // Loop over pairs with foreach foreach (KeyValuePair<string, int> pair in d) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } // Use var keyword to enumerate dictionary foreach (var pair in d) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); }

cat, 2 dog, 1 llama, 0 iguana, -1 cat, 2 dog, 1 llama, 0 iguana, -1

Sorted List Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index. A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values The capacity of a SortedList object is the number of elements the SortedList can hold. As elements are added to a SortedList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList object. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. However, the SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes. Different between Sorted List and Collection You can use the SortedList in the almost exact same way as a Dictionary, and its main difference is in its

implementation, which may require less memory for storage but more time for lookups.
Program that describes generic class [C#] Generics is a form of abstraction in developing code. Instead of writing a function or a class for a particular type, it can be written generally to use any type. When an instance of the generic class is instantiated, the type is specified. Type Safety

ArrayList stringList = new ArrayList(); 1. 2. 3. 4. 5. 6. 7. 8. stringList.Add(1); stringList.Add(2); stringList.Add(3); foreach (string i in stringList) //runtime error as collection contains an int { string theString = i; }

As ArrayList is not a type safe class the above code error will not be caught by the compiler. It will however throw a runtime error as you are attempting to cast an int object to a string object. Now see equivalent code using List<>, the generic version of the ArrayList class. 1. 2. 3. 4. 5. 6. 7. 8. 9. List<string> stringList = new List<string>(); stringList.Add(1); stringList.Add(2); stringList.Add(3); foreach (string i in stringList) { string theString = i; }

More elegant code & Performance Improvement. Microsoft lists performance improvement as a benefit of using generics due to the fact that since you specify your correct type or types at time of creation for an object there is no need to use casting as you can be guaranteed your object contains/uses items of a certain type. Casting requires boxing and unboxing. Boxing relates to converting a value type to a reference type while unboxing relates to converting a reference type to a value type. Both steal processor time and slow performance. Many developers however conclude that the performance benefit from using generics is negligible.
Introduction

In my previous article Working with Collections - ArrayList, I briefly described about ArrayList. In this article I am going to briefly describe about Generic List.
What is the problem?

In order to store ordered list of items (objects), we can simply use an ArrayList, however there are many disadvantages of using ArrayList particularly when you have a huge number of objects into it. The most

important is every time you need to cast them to get your actual object and this itself is a big overhead on the application. Also there is no type safety because you can store a string, an integer as well as a custom class into a single ArrayList that will not throw any error at compile time but you will get an exception at runtime if you were intended to store only integer in the ArrayList and were casting for integer object but someone had added string type of data also. The best solution in this scenario would be to restrict the type of object you are intended to store in your collections at the time of declaration itself so that it won't accept any other type of data.
a generic class is really just a class that accepts parameters This term conjures up a clearer metaphor for how the type parameters of a generic class serve as placeholders that get replaced by actual data types when a generic class is constructed As the projects get more complicated, programmers increasingly need a means to better reuse and customize their existing component-based software. To achieve such a high level of code reuse in other languages, programmers typically employ a feature called Generics. Using Generics, we can create class templates that support any type. When we instantiate that class, we specify the type we want to use, and from that point on, our object is "locked in" to the type we chose. using System; class Test<T> { T _value; public Test(T t) { // The field has the same type as the parameter. this._value = t; } public void Write() { Console.WriteLine(this._value); } } class Program { static void Main() { // Use the generic type Test with an int type parameter. Test<int> test1 = new Test<int>(5); // Call the Write method. test1.Write(); // Use the generic type Test with a string type parameter. Test<string> test2 = new Test<string>("cat");

} } Output 5 cat

test2.Write();

Generic classes with example in c# Generic classes provide generic nature to classes and data member datatypes. When creating Generic classes we will create classes, data members ... we will define with place holders <> Class classname <Placeholder> { ... } While creating object for the generic class we will specify the data type, then onwards class will bind to specific data type classname<int> obj = new classname<int>(); Example public class Generic<T> { // Data Member T empID; // Constructor public Generic(T eVal) { empID = eVal; } public void Show() { Console.WriteLine("Employee Id - {0}", empID); } } public class MainClass { public static void Main() { Generic<int> genObj1=new Generic<int>(20); genObj1.Show(); Generic<string> genObj2=new Generic<string>("EMP1"); genObj2.Show();

} }

using System; public class Exercise { public void Show<TypeOfValue>(string msg, TypeOfValue value) { Console.WriteLine("{0}: {1}", msg, value); } } public class Program { static int Main() { Exercise exo = new Exercise(); string message = "Integer"; const int iValue = 246; exo.Show<int>(message, iValue); message = "Character"; const char cValue = 'G'; exo.Show<char>(message, cValue); message = "Decimal"; const double dValue = 355.65; exo.Show<double>(message, dValue); } } return 0;

Practical Learning: Creating and Using a Method With Various Parameters 1. To create and use a method with various parameters, make the following changes:
namespace CommercialStore1 { public class Exercise { . . . public void ShowItem<T>(string content, int index, T item) { Console.WriteLine("{0}: {1} {2}", content, index, item); }

} class Program { static int Main(string[] args) { . . . for (int i = 0; i < exo.Count(); i++) { Exercise.CItem One = exo.Retrieve(i); } exo.ShowItem<double>("Item", i+1, One.Item);

Console.WriteLine("\nNumber of Items: {0}\n", exo.Count()); return 0; } } }

Advantages Help to make the code in the software components much more reusable. High Quality Code and Code Maintainability No runtime Casting No Boxing hence Allows Performance Efficiency Creates Type safe at compile time as generics specify type at runtime Programmer has stronger and flexible control over the code The stronger type checking associated with generics helps in finding errors easily at compile time only. No code Duplication Generics refer to classes and methods that work consistently on values of different types. Best Practices to use 1. If the data type contains Collection Type or any unspecified data types, then create a generic type. 2. If the data type will be operating on value types, then using generics will prevent the boxing and un boxing operations. 3. If the code contains multiple classes to handle different data types on which they operate then it is best practice to use Generics.

Listing 3: Implementing a generic method


using System; using System.Collections.Generic; class Test { static void Main( string[] args ) { Test t = new Test();

int[] integerArray = {1,2,3,4,5,6}; char[] characterArray = { 'J', 'O', 'Y', 'D', 'I','P' }; double[] doubleArray = {0.1,0.2,0.3,0.4,0.5,0.6}; Console.WriteLine( "Displaying the contents of the integer array:--" ); t.Display(integerArray); Console.WriteLine( "Displaying the contents of the character array:--" ); t.Display(characterArray); Console.WriteLine( "Displaying the contents of the double array:--" ); t.Display(doubleArray); } public void Display< GenericArray >( GenericArray[] array ) { for (int i = 0; i< array.Length; i++) Console.WriteLine(array[i]); } }

The following points sum up the basic advantages of using Generics. Code Efficiency Enhanced performance Type Safety and reliability Maintainability of code

Implementing a Generic Stack Class [ Back To Top ] Let us understand the Generics with a simple example. Here I have implemented a stack in two different ways. A stack that can be recollected, works in the LIFO (Last-In-First-Out) principle. If we implement a stack that can accept any data type or object and store the same in to it, we have to opt for an object based stack (obviously if we are not using Generics). I have given here two code examples of a partial implementation of a stack. The first one is an object based stack and the next a generic stack. The object based stack would require boxing and unboxing operations to store and return objects in and out of the stack, but the generic stack (the one that uses C# Generics) would not. Hence, as far as performance is concerned, the generic stack is the better choice. The code in Listing 4 is an example of an object based stack. Note that we can store any type of data in this stack, but we need to perform an explicit cast in order to retrieve the right type of the object that was stored using boxing and unboxing. This can be a significant performance overhead. Listing 4
using System; using System.Collections.Generic; using System.Text; namespace Generics {

public class CustomStack { const int size = 10; private object[] register; private int count = 0; private CustomStack() { register = new object[size]; } public void Push(object x) { if (count < size) register[count++] = x; } public object Pop() { return register[--count]; } static void Main(string[] args) { CustomStack intStack = new CustomStack(); intStack.Push(10); int i = (int)intStack.Pop(); Console.WriteLine(i); Console.Read(); } } }

When using the object based stack shown in Listing 1, you have to box and unbox the elements in order to push and pop them in and out of the stack resulting in a significant performance drawback. Now, Generics comes to the rescue. It is much more flexible and removes the overhead involved in boxing and unboxing operations that we discussed earlier as a generic type is assigned a specific type only at runtime. The type checks are done at the compile time itself. Hence, the generic stack in our example works much faster compared to its non-generic counterpart. The following is the implementation of a generic stack using C# Generics. Listing 5
using System; using System.Collections.Generic; using System.Text; namespace Generics { public class CustomStack<S> { const int size = 10; private S[] register; private int count = 0; public CustomStack() { register = new S[size]; } public void Push(S x)

{ if (count < size) register[count++] = x; } public S Pop() { return register[--count]; } } public class Test { static void Main(string[] args) { CustomStack<int> intStack = new CustomStack<int>(); intStack.Push(10); int i = intStack.Pop(); Console.WriteLine(i); Console.Read(); } } }

using System; class OverloadedMethods { static void Main( string[] args ) { // create arrays of int, double and char int[] intArray = { 1, 2, 3, 4, 5, 6 }; double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; char[] charArray = { 'H', 'E', 'L', 'L', 'O' }; Console.WriteLine( "Array intArray contains:" ); DisplayArray( intArray ); // pass an int array argument Console.WriteLine( "Array doubleArray contains:" ); DisplayArray( doubleArray ); // pass a double array argument Console.WriteLine( "Array charArray contains:" ); DisplayArray( charArray ); // pass a char array argument } // end Main // output int array static void DisplayArray( int[] inputArray ) { foreach ( int element in inputArray ) Console.Write( element + " " ); Console.WriteLine( "\n" ); } // end method DisplayArray // output double array static void DisplayArray( double[] inputArray ) { foreach ( double element in inputArray ) Console.Write( element + " " );

Console.WriteLine( "\n" ); } // end method DisplayArray // output char array static void DisplayArray( char[] inputArray ) { foreach ( char element in inputArray ) Console.Write( element + " " ); Console.WriteLine( "\n" ); } // end method DisplayArray } // end class OverloadedMethods

OUTPUT Array intArray contains: 123456 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array charArray contains: HELLO

Generic Method Implementation If the operations performed by several overloaded methods are identical for each argument type, the overloaded methods can be more compactly and conveniently coded using a generic method. You can write a single generic method declaration that can be called at different times with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. All generic method declarations have a type parameter list delimited by angle brackets (< E > in this example) that follows the method's name.

using System; using System.Collections.Generic; class GenericMethod { static void Main( string[] args ) { // create arrays of int, double and char int[] intArray = { 1, 2, 3, 4, 5, 6 }; double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; char[] charArray = { 'H', 'E', 'L', 'L', 'O' }; Console.WriteLine( "Array intArray contains:" ); DisplayArray( intArray ); // pass an int array argument Console.WriteLine( "Array doubleArray contains:" ); DisplayArray( doubleArray ); // pass a double array argument Console.WriteLine( "Array charArray contains:" );

DisplayArray( charArray ); // pass a char array argument } // end Main // output array of all types static void DisplayArray< E >( E[] inputArray ) { foreach ( E element in inputArray ) Console.Write( element + " " ); Console.WriteLine( "\n" ); } // end method PrintArray } // end class GenericMethod

Array intArray contains: 123456 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array charArray contains: HELLO

Remove duplicate items from Generic List


Most of times we use extensions like IList, IEnumerable, etc. which comes with .NET Framework 3.5. Other day when I was using these generic list with my custom class, I came across one of its shortcoming. Like it offers methods like Select(), Where() and GroupBy() which takes something called lambda as parameters. A few query operators, such as Distinct(), do not take lambdas as parameters. As a result, they are easy to call. The parameter less Distinct() removes duplicates from a list, based on their hash. Now this is all works fine when you use predefined data types for generic list. Trouble starts when you use your own class with generic list. At that time Distinct() most probably will not work. So we need some thing which actually removes duplicate entries from list. To solve this we can use IEqualityComparer which is also an parameter in Distinct() for one of the overloaded method. The Distinct() method with IEqualityComparer parameter returns an unordered sequence that contains no duplicate values. If comparer is null, the default equality comparer, Default, is used to compare values. Using this method one can avoid using lambda expressions. To understand the power of LINQ you do not need to understand lambdas. Lets see an example that will make this very clear. First we will create our class (we will create class for car) 1 public class Car 2 { 3 public string ModelName { get; set; } 4 public int Price { get; set; } 5 public string Type { get; set; }

6 } Then we have to create a class which will inherit IEqulityComparer and we have override two of their methods, namely Equals() and GetHashCode() 01 // Custom comparer for the Car class. 02 class CarComparer : IEqualityComparer 03 { // Cars are equal if their model names and car price are 04 equal. 05 public bool Equals(Car x, Car y) 06 { // Check whether the compared objects reference the same 07 data. 08 if (Object.ReferenceEquals(x, y)) return true; 09 10 // Check whether any of the compared objects is null. if (Object.ReferenceEquals(x, null) || 11 Object.ReferenceEquals(y, null)) 12 return false; 13 14 // Check whether the cars' properties are equal. 15 return x.ModelName == y.ModelName && x.Price == y.Price; 16 } 17 18 // If Equals() returns true for a pair of objects, 19 // GetHashCode must return the same value for these objects. 20 21 public int GetHashCode(Car car) 22 { 23 // Check whether the object is null. 24 if (Object.ReferenceEquals(car, null)) return 0; 25 // Get the hash code for the ModelName field if it is not 26 null. int hashModelName = car.ModelName == null ? 0 : 27 car.ModelName.GetHashCode(); 28 29 // Get the hash code for the price field. 30 int hashCarPrice = car.Price.GetHashCode(); 31 32 // Calculate the hash code for the product. 33 return hashModelName ^ hashCarPrice;

34 } 35 } Once we have defined the comparer, we can use IEnumerable sequence of Car objects in Distinct() method, as shown in the following example 01 List<Car> cars= { new Car { ModelName = "Merd", Price = 15000, Type = 02 "Basic" }, new Car { ModelName = "Ferrari", Price = 25000, Type = 03 "Pro" }, new Car { ModelName = "Porsche", Price = 50000, Type = 04 "Adv" }, new Car { ModelName = "Merd", Price = 15000, Type = 05 "Modern" }, new Car { ModelName = "Range Rover", Price = 77000, Type = 06 "Luxurious" } }; 07 08 //Exclude duplicates. 09 10 IEnumerable<Car> noduplicates = cars.Distinct(new CarComparer()); 11 12 foreach (var car in noduplicates) 13 Console.WriteLine(car.ModelName + " " + car.Price); 14 15 /* 16 This code produces the following output: 17 Merd 15000 18 Ferrari 25000 19 Porsche 50000 20 Range Rover 77000 21 */ Here we can notice that even Type property being different for ModelName "Merd" it only showed the first one, because we have defined the comparer only for two of its properties. If we will include the third property as well in comparer then it will show one more "Merd" in output of different type. My personal experience with this IEqualityComparer is that I had a parser which gave me records of around 2300+ for which I have used generic list with my custom class. To find duplicates was hell for me, because parameter less Distinct() didn't actually solved my problem. That's why I had to create custom comparer which solved my problem and amazing reduce the looping and no of duplicate records which reduced to around 300. Ohhhh....awesome! isn't it? Find more at http://msdn.microsoft.com/en-us/library/bb338049%28v=VS.90%29.aspx

C# Object Array
You want to use an object[] array in the C# programming language to store elements of different types in a single array. The object type and object arrays in the C# language provide a way to combine many object type instances into a single reference, with a cost to code simplicity and runtime performance. Here we look at object arrays.
Program that uses object[] array [C#] using System; using System.Text; class Program { static void Main() { // // Allocate an object array. // object[] array1 = new object[5]; // // - Put an empty object in the object array. // - Put various object types in the array. // - Put string literal in the array. // - Put an integer constant in the array. // - Put the null literal in the array. // array1[0] = new object(); array1[1] = new StringBuilder("Initialized"); array1[2] = "String literal"; array1[3] = 3; array1[4] = null; // // Use the object array reference as a parameter. // WriteArray(array1); } static void WriteArray(object[] array) { // // Loop through the objects in the array. // foreach (object element in array) { if (element != null) // Avoid NullReferenceException { Console.WriteLine(element.ToString()); Console.WriteLine(element.GetType()); Console.WriteLine("---"); } } } }

Output System.Object System.Object --Initialized System.Text.StringBuilder --String literal System.String --3 System.Int32 ---

Ienumereable List<T> implements IEnumerable<T>... basically IEnumerable<T> is just a sequence of items. You can read through it, and that's all. List<T> is a mutable collection - you can add to it, remove from it, sort it etc. It's more flexible in itself, but IEnumerable<T> allows you to use the same code to work with any implementation (arrays, linked lists, lists, iterators returned from methods using yield statements etc). Since IEnumerable<T> is immutable, you can use this interface when giving back data from your class knowing that no elements will be added or removed. Though the user can still call mutating functions on the objects contained within the enumerable. IEnumerable is an interface that allows the iteration through a collection of items (e.g. via the foreach keyword).

Iterate through a sorted dictionary by key C# 2.0


foreach (int rank in sortedStudents.Keys) { string student = sortedStudents[rank]; }

how to change the value of dictionary during looping


for (int i = 0; i < dtParams.Count; i++) { dtParams.Values.ElementAt(i).Replace("'", "''"); }

where dtParams is my Dictionary I want to do some thing like this:


string a = "car"; a = a.Replace("r","t");

FixedSizeCollection<T>: a generic .NET type /// <summary> /// A generic class to show instance counting /// </summary> /// <typeparam name="T">the type parameter used for the array storage</typeparam>public class FixedSizeCollection<T> { /// <summary> /// Constructor that increments static counter and sets up internal storage /// </summary> /// <param name="items"></param> public FixedSizeCollection(int items) { FixedSizeCollection<T>.InstanceCount++; this.Items = new T[items]; } /// <summary> /// Add an item to the class whose type /// is determined by the instantiating type /// </summary> /// <param name="item">item to add</param> /// <returns>the zero-based index of the item added</returns> public int AddItem(T item) { if (this.ItemCount < this.Items.Length) { this.Items[this.ItemCount] = item; return this.ItemCount++; } else throw new Exception("Item queue is full"); } /// <summary> /// Get an item from the class /// </summary> /// <param name="index">the zero-based index of the item to get</param> /// <returns>an item of the instantiating type</returns> public T GetItem(int index) { if (index >= this.Items.Length &&

index >= 0) throw new ArgumentOutOfRangeException("index"); return this.Items[index]; } #region Properties /// <summary> /// Static instance counter hangs off of the /// instantiated Type for /// GenericClass /// </summary> public static int InstanceCount { get; set; } /// <summary> /// The count of the items the class holds /// </summary> public int ItemCount{ get; private set; } /// <summary> /// The items in the class /// </summary> private T[] Items { get; set; } #endregion // Properties /// <summary> /// ToString override to provide class detail /// </summary> /// <returns>formatted string with class details</returns> public override string ToString() { return "There are " + FixedSizeCollection<T>.InstanceCount.ToString() + " instances of " + this.GetType().ToString() + " and this instance contains " + this.ItemCount + " items..."; } }

Collections Versus Generics in .NET


the real bottleneck on the Arraylist was during sorting and traversing the list. Each item is stored as an object, so it must be typed runtime, and then compared for sorting/searching. On the other side, the Generic List had all its items typed compile time, which saves alot of workload during sorting and searching.

Icomparable IComparable<T> interface on your class to allow a more intuitive way for the objects to be sorted in the C# language. When a class implements IComparable

Array size is fixed.But Linked is not fixed Linked List have an extra Overhead in its each node to store the pointer to the next node. Arrays have random access and less overheads compared to Linked list have sequential access only with too much overheads and no cache memory support. On the other hand, arrays allow random access, while linked lists allow only sequential access to elements. Singlylinked lists, in fact, can only be traversed in one direction. This makes linked lists unsuitable for applications where it's useful to look up an element by its index quickly, such as heapsort. Sequential access on arrays is also faster than on linked lists on many machines due to locality of reference and data caches. Linked lists receive almost no benefit from the cache. Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of
The main problem with ArrayList is that is uses object - it means you have to cast to and from whatever you are encapsulating. It is a remnant of the days before generics and is probably around for backwards compatibility only. You do not have the type safety with ArrayList that you have with a generic list. The performance issue is in the need to cast objects back to the original (or have implicit boxing happen). Implicit boxing will happen whenever you use a value type - it will be boxed when put into the ArrayList and unboxed when referenced. The issue is not just that of performance, but also of readablity and correctness. Since generics came in, this object has become obsolete and would only be needed in .NET 1.0/1.1 code.

What is the purpose of ArrayList in .NET?


ArrayList is used to store elements of different data types.

Advantage of ArrayList is that its size can grow or shrink dynamically. Here is an example using an ArrayList to store and read list of integers and list of strings: public class sampleClass { public static void displayList(ArrayList sampleList) { foreach(var element in sampleList) { Console.Write( + element); } } public static void Main() { ArrayList intList = new ArrayList(); intList.Add(10); intList.Add(20); Console.WriteLine(Elements of integer list are:); displayList(intList); ArrayList stringList = new ArrayList(); stringList.Add(Hello!); stringList.Add(Have a Nice Day!); Console.WriteLine(Elements of string list are:); displayList(stringList); } } Output of this code will be: Elements of integer list are: 10 20 Elements of string list are: Hello! Have a Nice Day! ArrayList has many methods like Clear(), AddRange(<list>), RemoveAt(<index>), Insert(<position, element>) and properties like count. You can use them to manipulate on ArrayList elements.

Vous aimerez peut-être aussi