首页 > 代码库 > 第六章 数组

第六章 数组

ArraySegmentSample

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArraySegmentSample
{
    class Program
    {
        static void Main()
        {
            int[] ar1 = { 1, 4, 5, 11, 13, 18 };
            int[] ar2 = { 3, 4, 5, 18, 21, 27, 33 };
            var segments = new ArraySegment<int>[2] 
            { 
                new ArraySegment<int>(ar1, 0, 3), 
                new ArraySegment<int>(ar2, 3, 3)
            };


            var sum = SumOfSegments(segments);
            Console.WriteLine("sum of all segments: {0}", sum);

        }

        static int SumOfSegments(ArraySegment<int>[] segments)
        {
            int sum = 0;
            foreach (var segment in segments)
            {
                for (int i = segment.Offset; i < segment.Offset + segment.Count; i++)
                {
                    sum += segment.Array[i];
                }

            }
            return sum;
        }
    }
}
View Code

SimpleArrays

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
  class Program
  {
    static void Main()
    {
      SimpleArrays();
      TwoDim();
      ThreeDim();
      Jagged();

      ArrayClass();
      CopyArrays();

    }

    static void CopyArrays()
    {
      Person[] beatles = {
                     new Person { FirstName="John", LastName="Lennon" },
                     new Person { FirstName="Paul", LastName="McCartney" }
                   };

      Person[] beatlesClone = (Person[])beatles.Clone();

    }

    static void ArrayClass()
    {
      Array intArray1 = Array.CreateInstance(typeof(int), 5);
      for (int i = 0; i < 5; i++)
      {
        intArray1.SetValue(33, i);
      }

      for (int i = 0; i < 5; i++)
      {
        Console.WriteLine(intArray1.GetValue(i));
      }

      int[] lengths = { 2, 3 };
      int[] lowerBounds = { 1, 10 };
      Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds);
      
      racers.SetValue(new Person { FirstName = "Alain", LastName = "Prost" }, index1: 1, index2: 10);
      racers.SetValue(new Person
      {
        FirstName = "Emerson",
        LastName = "Fittipaldi"
      }, 1, 11);
      racers.SetValue(new Person { FirstName = "Ayrton", LastName = "Senna" }, 1, 12);
      racers.SetValue(new Person { FirstName = "Michael", LastName = "Schumacher" }, 2, 10);
      racers.SetValue(new Person { FirstName = "Fernando", LastName = "Alonso" }, 2, 11);
      racers.SetValue(new Person { FirstName = "Jenson", LastName = "Button" }, 2, 12);

      Person[,] racers2 = (Person[,])racers;
      Person first = racers2[1, 10];
      Person last = racers2[2, 12];


    }

    static void Jagged()
    {
      int[][] jagged = new int[3][];
      jagged[0] = new int[2] { 1, 2 };
      jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };
      jagged[2] = new int[3] { 9, 10, 11 };

      for (int row = 0; row < jagged.Length; row++)
      {
        for (int element = 0;
           element < jagged[row].Length; element++)
        {
          Console.WriteLine(
             "row: {0}, element: {1}, value: {2}",
             row, element, jagged[row][element]);
        }
      }


    }

    static void ThreeDim()
    {
      int[, ,] threedim = {
                    { { 1, 2 }, { 3, 4 } },
                    { { 5, 6 }, { 7, 8 } },
                    { { 9, 10 }, { 11, 12 } }
                   };


      Console.WriteLine(threedim[0, 1, 1]);
    }

    static void TwoDim()
    {
      int[,] twodim = new int[3, 3];
      twodim[0, 0] = 1;
      twodim[0, 1] = 2;
      twodim[0, 2] = 3;
      twodim[1, 0] = 4;
      twodim[1, 1] = 5;
      twodim[1, 2] = 6;
      twodim[2, 0] = 7;
      twodim[2, 1] = 8;
      twodim[2, 2] = 9;






    }


    static void SimpleArrays()
    {
      Person[] myPersons = new Person[2];

      myPersons[0] = new Person { FirstName = "Ayrton", LastName = "Senna" };
      myPersons[1] = new Person { FirstName = "Michael", LastName = "Schumacher" };

      Person[] myPersons2 = 
            { 
                new Person { FirstName="Ayrton", LastName="Senna"},
                new Person { FirstName="Michael", LastName="Schumacher"} 
            };
    }
  }
}
View Code
技术分享
using System;

namespace Wrox.ProCSharp.Arrays
{
  public class Person
  {
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public override string ToString()
    {
      return String.Format("{0} {1}", FirstName, LastName);
    }
  }

}
View Code

SortingSample

技术分享
using System;

namespace Wrox.ProCSharp.Arrays
{


    class Program
    {
        static void Main()
        {
            SortNames();
            Person[] persons = GetPersons();
            SortPersons(persons);
            Console.WriteLine();
            SortUsingPersonComparer(persons);
        }


        static void SortUsingPersonComparer(Person[] persons)
        {
            Array.Sort(persons, 
                new PersonComparer(PersonCompareType.FirstName));

            foreach (Person p in persons)
            {
                Console.WriteLine(p);
            }

        }

        static Person[] GetPersons()
        {
            return new Person[] {
                new Person { FirstName="Damon", LastName="Hill" },
                new Person { FirstName="Niki", LastName="Lauda" },
                new Person { FirstName="Ayrton", LastName="Senna" },
                new Person { FirstName="Graham", LastName="Hill" }
             };
        }

        static void SortPersons(Person[] persons)
        {
            Array.Sort(persons);
            foreach (Person p in persons)
            {
                Console.WriteLine(p);
            }
        }

        static void SortNames()
        {
            string[] names = {
                   "Christina Aguilera",
                   "Shakira",
                   "Beyonce",
                   "Gwen Stefani"
                 };

            Array.Sort(names);

            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

        }
    }
}
View Code
技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
    public enum PersonCompareType
    {
        FirstName,
        LastName
    }

    public class PersonComparer : IComparer<Person>
    {
        private PersonCompareType compareType;

        public PersonComparer(PersonCompareType compareType)
        {
            this.compareType = compareType;
        }


        #region IComparer<Person> Members

        public int Compare(Person x, Person y)
        {
            if (x == null) throw new ArgumentNullException("x");
            if (y == null) throw new ArgumentNullException("y");

            switch (compareType)
            {
                case PersonCompareType.FirstName:
                    return x.FirstName.CompareTo(y.FirstName);
                case PersonCompareType.LastName:
                    return x.LastName.CompareTo(y.LastName);
                default:
                    throw new ArgumentException(
                          "unexpected compare type");
            }
        }

        #endregion
    }

}
View Code
技术分享
using System;

namespace Wrox.ProCSharp.Arrays
{
    public class Person : IComparable<Person>
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public override string ToString()
        {
            return String.Format("{0} {1}",
                  FirstName, LastName);
        }

        public int CompareTo(Person other)
        {
            if (other == null) throw new ArgumentNullException("other");

            int result = this.LastName.CompareTo(other.LastName);
            if (result == 0)
            {
                result = this.FirstName.CompareTo(other.FirstName);
            }

            return result;
        }
 
    }
}
View Code
技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
    public class Musician : Person
    {
    }
}
View Code

StructuralComparison

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
  public class Person : IEquatable<Person>
  {
    public int Id { get; private set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
      return String.Format("{0}, {1} {2}", Id, FirstName, LastName);
    }

    //public override bool Equals(object obj)
    //{
    //    if (obj == null) 
    //        return base.Equals(obj);
    //    return Equals(obj as Person);
    //}

    //public override int GetHashCode()
    //{
    //    return Id.GetHashCode();
    //}

    #region IEquatable<Person> Members

    public bool Equals(Person other)
    {
      if (other == null)
        return base.Equals(other);

      return this.FirstName == other.FirstName && this.LastName == other.LastName;
    }

    #endregion
  }

}
View Code
技术分享
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
  class TupleComparer : IEqualityComparer
  {
    #region IEqualityComparer Members

    public new bool Equals(object x, object y)
    {
      bool result = x.Equals(y);
      return result;
    }

    public int GetHashCode(object obj)
    {
      return obj.GetHashCode();
    }

    #endregion
  }


  class Program
  {
    static void Main()
    {
      var janet = new Person { FirstName = "Janet", LastName = "Jackson" };
      Person[] persons1 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet };
      Person[] persons2 = { new Person { FirstName = "Michael", LastName = "Jackson" }, janet };
      if (persons1 != persons2)
        Console.WriteLine("not the same reference");

      if (!persons1.Equals(persons2))
        Console.WriteLine("equals returns false - not the same reference");

      if ((persons1 as IStructuralEquatable).Equals(persons2, EqualityComparer<Person>.Default))
      {
        Console.WriteLine("the same content");
      }


      var t1 = Tuple.Create<int, string>(1, "Stephanie");
      var t2 = Tuple.Create<int, string>(1, "Stephanie");
      if (t1 != t2)
        Console.WriteLine("not the same reference to the tuple");

      if (t1.Equals(t2))
        Console.WriteLine("equals returns true");

      TupleComparer tc = new TupleComparer();

      if ((t1 as IStructuralEquatable).Equals(t2, tc))
      {
        Console.WriteLine("yes, using TubpleComparer");
      }

    }
  }
}
View Code

TuplesSample

技术分享
using System;

namespace TuplesSample
{
  class Program
  {
    static void Main()
    {
      Tuple<string, string> name = new Tuple<string, string>("Jochen", "Rindt");
      Console.WriteLine(name.ToString());

      var result = Divide(5, 2);
      Console.WriteLine("result of division: {0}, reminder: {1}", result.Item1, result.Item2);

      AnyElementNumber();
    }

    static void AnyElementNumber()
    {
      var tuple = Tuple.Create<string, string, string, int, int, int, double, Tuple<int, int>>(
          "Stephanie", "Alina", "Nagel", 2009, 6, 2, 1.37, Tuple.Create<int, int>(52, 3490));
      Console.WriteLine(tuple.Item1);
    }

    public static Tuple<int, int> Divide(int dividend, int divisor)
    {
      int result = dividend / divisor;
      int reminder = dividend % divisor;

      return Tuple.Create<int, int>(result, reminder);
    }
  }
}
View Code

YieldDemo

技术分享
using System;
using System.Collections;
using System.Collections.Generic;

namespace Wrox.ProCSharp.Arrays
{
  public class HelloCollection
  {
    public IEnumerator<string> GetEnumerator()
    {
      yield return "Hello";
      yield return "World";
    }
  }


  class Program
  {
    static void Main()
    {
      HelloWorld();
      MusicTitles();

      var game = new GameMoves();

      IEnumerator enumerator = game.Cross();
      while (enumerator.MoveNext())
      {
        enumerator = enumerator.Current as IEnumerator;
      }
    }

    static void MusicTitles()
    {
      var titles = new MusicTitles();
      foreach (var title in titles)
      {
        Console.WriteLine(title);
      }
      Console.WriteLine();

      Console.WriteLine("reverse");
      foreach (var title in titles.Reverse())
      {
        Console.WriteLine(title);
      }
      Console.WriteLine();

      Console.WriteLine("subset");
      foreach (var title in titles.Subset(2, 2))
      {
        Console.WriteLine(title);
      }

    }

    static void HelloWorld()
    {
      var helloCollection = new HelloCollection();
      foreach (string s in helloCollection)
      {
        Console.WriteLine(s);
      }
    }
  }
}
View Code
技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
  public class MusicTitles
  {
    string[] names = {
              "Tubular Bells", "Hergest Ridge",
              "Ommadawn", "Platinum" };

    public IEnumerator<string> GetEnumerator()
    {
      for (int i = 0; i < 4; i++)
      {
        yield return names[i];
      }
    }

    public IEnumerable<string> Reverse()
    {
      for (int i = 3; i >= 0; i--)
      {
        yield return names[i];
      }
    }

    public IEnumerable<string> Subset(int index, int length)
    {
      for (int i = index; i < index + length;
                i++)
      {
        yield return names[i];
      }
    }
  }
}
View Code
技术分享
using System;
using System.Collections;
using System.Linq;
using System.Text;

namespace Wrox.ProCSharp.Arrays
{
  public class GameMoves
  {
    private IEnumerator cross;
    private IEnumerator circle;

    public GameMoves()
    {
      cross = Cross();
      circle = Circle();
    }

    private int move = 0;
    const int MaxMoves = 9;

    public IEnumerator Cross()
    {
      while (true)
      {
        Console.WriteLine("Cross, move {0}", move);
        if (++move >= MaxMoves)
          yield break;
        yield return circle;
      }
    }

    public IEnumerator Circle()
    {
      while (true)
      {
        Console.WriteLine("Circle, move {0}", move);
        if (++move >= MaxMoves)
          yield break;
        yield return cross;
      }
    }
  }

}
View Code

 

第六章 数组