C # list of sets,

Source: Internet
Author: User

C # list of sets,

. NET Framework provides a List of generic classes for the dynamic List <T>. This class implements the IList, ICollection, IEnumerable, IList <T>, ICollection <T>, and IEnumerable <T> interfaces.
1. Create a list
Create a racing driver class, which will be used in the following example:

   public class Racer : IComparable<Racer>, IFormattable      {        public int Id { get; private set; }        public string FirstName { get; set; }        public string LastName { get; set; }        public string Country { get; set; }        public int Wins { get; set; }        public Racer(int id, string firstName, string lastName, string country)          : this(id, firstName, lastName, country, wins: 0)        {        }        public Racer(int id, string firstName, string lastName, string country, int wins)        {          this.Id = id;          this.FirstName = firstName;          this.LastName = lastName;          this.Country = country;          this.Wins = wins;        }        public override string ToString()        {          return String.Format("{0} {1}", FirstName, LastName);        }        public string ToString(string format, IFormatProvider formatProvider)        {          if (format == null) format = "N";          switch (format.ToUpper())          {            case null:            case "N": // name              return ToString();            case "F": // first name              return FirstName;            case "L": // last name              return LastName;            case "W": // Wins              return String.Format("{0}, Wins: {1}", ToString(), Wins);            case "C": // Country              return String.Format("{0}, Country: {1}", ToString(), Country);            case "A": // All              return String.Format("{0}, {1} Wins: {2}", ToString(), Country, Wins);            default:              throw new FormatException(String.Format(formatProvider,                    "Format {0} is not supported", format));          }        }        public string ToString(string format)        {          return ToString(format, null);        }        public int CompareTo(Racer other)        {          if (other == null) return -1;          int compare = string.Compare(this.LastName, other.LastName);          if (compare == 0)            return string.Compare(this.FirstName, other.FirstName);          return compare;        }      }

 

By calling the default constructor, you can create a list object. In List <T>, the type must be specified for the value declared as List:
Var intList = new List <int> ();
Var racers = new List <Racer> ();
Use the default constructor to create an empty list. After an element is added to the list, the capacity of the List is expanded to four acceptable elements. If you add the fifth element, the size of the List is reset to eight elements. If eight elements are not enough, the size of the list will be reset to include 16 elements. Each time, the list capacity is reset to twice the original capacity.
If the capacity of the list changes, the entire set will be reassigned to a new memory block. In the implementation code of List <T> generic classes, a T-type array is used. By re-allocating memory, create a new Array. The Array. Copy () method copies the elements in the old Array to the new Array. To save time, if you know the number of elements in the list in advance, you can use the constructor to define its capacity:
List <int> intList = new List <int> (10 );
You can use the Capacity attribute to get and set the Capacity of the Set:
IntList. Capacity = 20;
The number of elements in the set is read using the Count attribute.

If you have added an element to the list and do not want to add more elements, you can call the TrimExcess () method to remove unnecessary capacity. However, it takes time to relocate the element. If the number of elements exceeds 90% of the capacity, this method will do nothing.
IntList. TrimExcess ();

You can also assign values to the set by using the initial value of the Set:
Var intList = new List <int> () {1, 2 };
The initial value of the set is not reflected in the IL code of the compiled assembly. The compiler will change the initial value of the set to call the Add () method for each item in the Initial Value List.

2. Add Elements
You can use the Add () method to Add elements to the list:
IntList. Add (1 );
IntList. Add (2 );

Using the AddRange () method, you can add multiple elements to the set at a time. Because the parameters of the AddRange () method are IEnumerable <T> type objects, you can pass an array:
IntList. AddRange (
New Int [] {1, 2}
);
If you know the number of elements in the set when instantiating the list, you can also pass the IEnumerable <T> type object to the class constructor, similar to the AddRange () method:
Var intList = new List <int> (
New Int [] {1, 2}
);

3. insert element
You can use the Insert () method to Insert an element at a specified position:
IntList. Insert (3, 4 );
Method InsertRange () can insert a large number of elements.
Racers. InsertRange (3, new Racer [] {
New Racer (12, "Jochen", "Rindt", "Austria", 6 ),
New Racer (22, "Ayrton", "Senna", "Brazil", 41 )});

4. Access Element
All classes that implement the IList and IList <T> interfaces provide an indexer that can be used to access elements:
Int I = intList [0;]
The String class can also access characters through indexes:
String s = "sdas ";
Char c = s [0];

Because the List <T> collection class implements the IEnumerable interface, you can also use a foreach (http://www.cnblogs.com/afei-24/p/6738155.html) statement to traverse the elements in the Set:
Foreach (int I in intList)
{
//..
}
In addition to the foreach statement, the List <T> class also provides the ForEach () method, which is declared using the Action <T> parameter:
Public void ForEach (Action <T> action );
The code for implementing the ForEach () method in. NEt is as follows:
Public class List <T>: ILIst <T>
{
Private T [] items;

//...

Public void ForEach (Action <T> action)
{
If (action = null) throw new ArgumentNullException ("action ");

Foreach (T item in items)
{
Action (item );
}
}
}

Instance:
Racers. ForEach (
R =>
{
Console. WriteLine (r. ToString ())
}
);
Lambda expressions (http://www.cnblogs.com/afei-24/p/6795233.html) are used here ).

5. Delete Elements
When deleting an element, you can use the index or pass the element to be deleted:
Var graham = new Racer (7, "Graham", "Hill", "UK", 14 );
Var emerson = new Racer (13, "Emerson", "Fittipaldi", "Brazil", 14 );
Var mario = new Racer (16, "Mario", "Andretti", "USA", 12 );
Var racers = new List <Racer> (20) {graham, emerson, mario };
Racers. RemoveAt (3 );
Racers. Remove (graham );

Deleting by index is faster, because you must search for the elements to be deleted in the set. The Remove Method first searches in the Set, uses the IndexOf method to obtain the index of the element, and then deletes the element using the index. The IndexOf method first checks whether the element type implements the IEquatable <T> interface. If yes, call the Equals () method of this interface to determine whether the element in the set is equal to the element passed to the Equals () method. If this interface is not implemented, use the Equals () method of the Object class to compare these elements. By default, the Equals () method of the Object class compares the value types by bit, and only compares the referenced types.

The RemoveRange () method can delete many elements from a collection. Its first parameter specifies the element index to be deleted, and the second parameter specifies the number of elements to be deleted:
Int index = 3;
Int count = 5;
Racers. RemoveRange (index, count );
To delete all elements in the set, you can use the Clear () method defined by the ICollection <T> interface:
Racers. Clear ();
The RemoveAll () method deletes elements with specified features. This method uses the Parameter definition of the Predicate <T> type. The following describes the Predicate <T> type.

6. Search
Obtain the index of the element to be searched, or the element itself. Available methods include IndexOf (), LastIndexOf (), FindIndex (), FindLastIndex (), Find (), FindLast ().
If you only check whether the element Exists, you can use the Exists () method.

The IndexOf () method needs to take an object as a parameter. If this element is found in the Set, this method returns the index of this element. If no value is found, the-1. IndexOf method is returned and the IEquatable <T> interface is used to compare elements.
Using the IndexOf () method, you can also specify the element from which to start searching and several elements without searching the entire set.

In addition to using the IndexOf () method to search for specified elements, you can also search for elements with a certain feature. For this feature, you can use FindIndex (), FindLastIndex (), Find (), FindLast () methods. These methods require a Predicate <T> type parameter:
For example:
Public int FindIndex (Predicate <T> match );
The Predicate <T> type is a delegate: public delegate bool Predicate <T> (T obj );
The method is similar to the Action Delegate of the Foreach () method. If the Predicate <T> delegate returns true, there is a matching element. If false is returned, no search is found.
The FindIndex () and FindLastIndex () Methods return an index of the matched element. Find () and FindLast () return the matched element.

If you want to obtain all the items that match Predicate <T>, instead of one item, you can use the FindAll () method. The FindAll () method is used in the same way. The FindAll () method does not stop after finding the first item, but continues to iterate each item in the Set:
List <Racer> l = racers. FindAll (r => r. Wins> 20 );

7. Sorting
The List <T> class can use the Sort () method to Sort the elements in the set. The Sort () method uses the Quick Sort Algorithm for sorting.
The Sort () method has multiple overloaded methods. You can pass the generic delegate Comparison <T> and generic interface IComparer <T>, And a range value and generic interface IComparer <T>:
Public void List <T>. Sort ();
Public void List <T>. Sort (Comparison <T> );
Public void List <T>. Sort (IComparer <T> );
Public void List <T>. Sort (Int32, Int32, IComparer <T> );
Only when the elements in the Set implement the IComparable interface can the Sort () method without parameters be used.

Use public void List <T>. sort (IComparer <T>); you need to define a class that implements the IComparer <T> interface and call Sort (IComparer <T>) the Compare method in the class that implements the IComparer <T> interface is called:

      public class RacerComparer : IComparer<Racer>          {             public enum CompareType              {                FirstName,                LastName,                Country,                Wins              }            private CompareType compareType;            public RacerComparer(CompareType compareType)            {              this.compareType = compareType;            }            public int Compare(Racer x, Racer y)            {              if (x == null && y == null) return 0;              if (x == null) return -1;              if (y == null) return 1;              int result;              switch (compareType)              {                case CompareType.FirstName:                  return string.Compare(x.FirstName, y.FirstName);                case CompareType.LastName:                  return string.Compare(x.LastName, y.LastName);                case CompareType.Country:                  result = string.Compare(x.Country, y.Country);                  if (result == 0)                    return string.Compare(x.LastName, y.LastName);                  else                    return result;                case CompareType.Wins:                  return x.Wins.CompareTo(y.Wins);                default:                  throw new ArgumentException("Invalid Compare Type");              }            }          }

Client code:
Racers. Sort (new RacerComparer (RacerComparer. CompareType. Country ));

Use public void List <T>. Sort (Comparison <T>); a Comparison <T> delegate is required. Comparison <T> delegate: public delagate int Comparsion <T> (int x, int y );
Client code:
Racers. Sort (r1, r2) => r2.Wins. CompareTo (r1.Wins ));


The Reverse () method can be used to Reverse the order of the entire set.

8. type conversion
Use the ConvertAll <TOutput> () method of the List <T> class to convert the set of so types to another type. The ConvertAll <TOutput> () method uses the Converte delegate. The Converte delegate: public sealed delegate TOutput Converter <TInput, TOutput> (TInput from );

// Define a Person class public class Person {private string name; public Person (string name) {this. name = name;} public override string ToString () {return name ;}}

Client code:
List <Person> persons =
Racers. ConvertAll <Person> (
R => new Person (r. FiastName + "" + r. LastName)
);

9. Read-only set
After a set is created, it can be read and written. However, after filling in the set, you can use the AsReadOnly () method to create a read-only set.
List <Racer> racers2 = racers. AsReadOnly ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.