C# Collections

Collections are based on the ICollection interface, the IList interface, the IDictionary interface, or their generic counterparts. The IList interface and the IDictionary interface are both derived from the ICollection interface; therefore, all collections are based on the ICollection interface either directly or indirectly. In collections based on the IList interface (such as Array, ArrayList, or List<T>) or directly on the ICollection interface (such as Queue, ConcurrentQueue<T>, Stack, ConcurrentStack<T> or LinkedList<T>), every element contains only a value. In collections based on the IDictionary interface (such as the Hashtable and SortedList classes, the Dictionary<TKey, TValue> and SortedList<TKey, TValue> generic classes), or the ConcurrentDictionary<TKey, TValue> classes, every element contains both a key and a value. The KeyedCollection<TKey, TItem> class is unique because it is a list of values with keys embedded within the values and, therefore, it behaves like a list and like a dictionary.

Generic collections are the best solution to strong typing. However, if your language does not support generics, the System.Collections namespace includes base collections, such as CollectionBase, ReadOnlyCollectionBase, and DictionaryBase, which are abstract base classes that can be extended to create collection classes that are strongly typed. When efficient multi-threaded collection access is required, use the generic collections in the System.Collections.Concurrent namespace.

Collections can vary, depending on how the elements are stored, how they are sorted, how searches are performed, and how comparisons are made. The Queue class and the Queue<T> generic class provide first-in-first-out lists, while the Stack class and the Stack<T> generic class provide last-in-first-out lists. The SortedList class and the SortedList<TKey, TValue> generic class provide sorted versions of the Hashtable class and the Dictionary<TKey, TValue> generic class. The elements of a Hashtable or a Dictionary<TKey, TValue> are accessible only by the key of the element, but the elements of a SortedList or a KeyedCollection<TKey, TItem> are accessible either by the key or by the index of the element. The indexes in all collections are zero-based, except Array, which allows arrays that are not zero-based.

The LINQ to Objects feature allows you to use LINQ queries to access in-memory objects as long as the object type implements IEnumerable or IEnumerable<T>. LINQ queries provide a common pattern for accessing data; are typically more concise and readable than standard foreach loops; and provide filtering, ordering and grouping capabilities. LINQ queries can also improve performance. For more information, see LINQ to Objects and Parallel LINQ (PLINQ).


Title Description
Collections and Data Structures Discusses the various collection types available in the .NET Framework, including stacks, queues, lists, arrays, and dictionaries.
Hashtable and Dictionary Collection Types Describes the features of generic and nongeneric hash-based dictionary types.
Sorted Collection Types Describes classes that provide sorting functionality for lists and sets.
Generics in the .NET Framework Describes the generics feature, including the generic collections, delegates, and interfaces provided by the .NET Framework. Provides links to feature documentation for C#, Visual Basic, and Visual C++, and to supporting technologies such as reflection.

Object-Oriented Programming (OOP)

Class – defines the grouping of data and code, the “type” of an object
Instance – a specific allocation of a class
Message – sent to objects to make them act
Method – a “function” that an object knows how to perform
Instance Variables – a specific piece of data belonging to an object
Property – away to access instance variables and other attributes of an object
Encapsulation – keep implementation private and seperate from interface
Polymorphism – different objects, same interface
Inheritance – hierarchical organization. share code, customize or extend behaviors

C# == operator

static void Main(string[] args)
{
// 값형식과 참조형식
int val1 = 5;
int val2 = 10;
if (val1 == val2) // false (val1과 val2는 값이 다름)
Console.WriteLine(“val1 == val2”);
else
Console.WriteLine(“val1 != val2”);
object val3 = val1;
object val4 = val1;
if (val3 == val4) // false (val3와 val4는 같은 곳을 참조하지 않음)
Console.WriteLine(“val3 == val4”);
else
Console.WriteLine(“val3 != val4”);

int val5 = (int)val3;
int val6 = (int)val4;
if (val5 == val6) // true (val5와 val6은 같은 값을 가짐)
Console.WriteLine(“val5 == val6”);
else
Console.WriteLine(“val5 != val6”);

Point pos1 = new Point(val1, val2);
Point pos2 = new Point(val1, val2);
if (pos1 == pos2) // false (만약 Point Class가 ==연산자와 != 연산자와 Equals와 GetHashCode를 구현하지 않았다면 같은 곳을 참조하고 있지 않음) true (만약 Point Class가 데이터의 내용이 같은지를 판별하는 ==연산자와 !=연산자와 Equals와 GetHashCode를 구현했다면)
Console.WriteLine(“pos1 == pos2”);
else
Console.WriteLine(“pos1 != pos2”);
if (pos1.X == pos2.X) // true
Console.WriteLine(“pos1.X == pos2.X”);
else
Console.WriteLine(“pos1.X != pos2.X”);
if (pos1.Y == pos2.Y) // true
Console.WriteLine(“pos1.Y == pos2.Y”);
else
Console.WriteLine(“pos1.Y != pos2.Y”);

Point pos3 = pos1;
Point pos4 = pos1;
if (pos3 == pos4) // true (pos3와 pos4는 같은 곳을 참조하고 있음)
Console.WriteLine(“pos3 == pos4”);
else
Console.WriteLine(“pos3 != pos4”);

object pos5 = pos3;
object pos6 = pos4;
if (pos5 == pos6) // true (pos5와 pos6는 같은 곳을 참조하고 있음)
Console.WriteLine(“pos5 == pos6”);
else
Console.WriteLine(“pos5 != pos6”);

Point pos7 = (Point)pos6;
if (pos1 == pos7) // true (pos1, pos3, pos4, pos6, pos7는 같은 곳을 참조하고 있음)
Console.WriteLine(“pos1 == pos7”);
else
Console.WriteLine(“pos1 != pos7”);
if (pos2 == pos7) // false (만약 Point Class가 ==연산자와 != 연산자와 Equals와 GetHashCode를 구현하지 않았다면 같은 곳을 참조하고 있지 않음) true (만약 Point Class가 데이터의 내용이 같은지를 판별하는 ==연산자와 !=연산자와 Equals와 GetHashCode를 구현했다면)
Console.WriteLine(“pos2 == pos7”);
else
Console.WriteLine(“pos2 != pos7”);

C# ==operator vs Equals

http://msdn.microsoft.com/en-us/library/ms173147.aspx

// Operator Overloading
if (x == y) { // 컴파일시 x와 y가 동일한지 확인

// 참조형일 경우
object x = “hello”;
object y = ‘h’ + “ello”; // ensure it’s a different reference
if (x == y) { // 결과 => FALSE
if (x.Equals(y)) { // 결과 => TRUE

// string 형(참조형이긴 하지만)일 경우
// Equals와 equality operators (== and !=) 을 구현하여 string 객체의 값이 동일한지 확인
string x1 = “hello”;
string y1 = ‘h’ + “ello”; // ensure it’s a different reference
if (x1 == y1) { // 결과 => TRUE
if (x1.Equals(y1)) { // 결과 => TRUE

Dictionary

using System.Collections.Generic;

static Dictionary<string, FigureType> figureNameDic = new Dictionary<string, FigureType>();

static void SetFigureNameDictionary()
{
figureNameDic.Add(“삼각형”, FigureType.Triangle);
figureNameDic.Add(“Triangle”, FigureType.Triangle);
figureNameDic.Add(“TRIANGLE”, FigureType.Triangle);
figureNameDic.Add(“정사각형”, FigureType.Square);
figureNameDic.Add(“Square”, FigureType.Square);
figureNameDic.Add(“SQUARE”, FigureType.Square);
// 중간 생략…
}

 

C# Array/ArrayList

Person[] pArray = new Person[5];

// 만약 Person 객체를 하나만 생성한 후 for문에서 공유해 사용할 경우
// 마지막으로 입력된 데이터로 모든 데이터값이 치환됨
Person p = new Person();
for (int i = 0; i < 5; i++) {
p.Name = Console.ReadLine();           // 입력정보
p.age = int.Parse(Console.ReadLine()); // 입력정보
pArray[i] = p;                                  // 리스트에 들어간 모든 원소는 동일한 p
}

 

Person[] pArray = new Person[5];

// 아래와 같이 for문 안에 Person p = new Person()와같이 새로운 객체를 생성해야
// 각자 다르게 입력된 정보가 들어가게 됨
for (int i = 0; i < 5; i++) {
Person p = new Person();
    p.Name = Console.ReadLine();           // 입력정보
p.age = int.Parse(Console.ReadLine()); // 입력정보
pArray[i] = p;                                  // 이때 p는 새로운 Person객체
}


http://dis.dankook.ac.kr/lectures/hci10/entry/C-ArrayList
 (ArrayList 사용예)

ArrayList

using System.Collections;

ArrayList figureCalcList = new ArrayList();
do
{
/// 중간 생략
FigureCalculator calc = FigureCalculatorFactory.GetInstance(inputFigure);
figureCalcList.Add(calc);
/// 중간 생략
} while (Console.ReadKey().Key != ConsoleKey.Escape);

foreach (var calc in figureCalcList)
{
/// 중간 생략 – 출력
}

Car class property

class Car
{
// member field
//string name;
//int year;
/*
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public int Year
{
get
{
return this.year;
}
set
{
this.year = value;
}
}
*/

// property
public string Name
{
get;
set;
}
public int Year
{
get;
set;
}

 

// constructor
public Car() : this(“Avante”, 2013)
{
}

 

public Car(string name, int year)
{
this.Name = name;
this.Year = year;
}

 

// method
public void Print()
{
Console.WriteLine(“자동차 {0} 년도 {1}”, this.Name, this.Year);
}
}

 

 

 

class Program
{
static void Main(string[] args)
{
Car c1 = new Car();
c1.Print();
c1.Name = “Accent”;
c1.Print();
Console.WriteLine(c1.Name);
Car c2 = new Car(“Sonata”, 2012);
c2.Print();
}

Inheritance

class Person
{
private string name; // 파상클래스에 상속 안됨
protected int age; // 파생클래스에 상속 됨

public Person() : this(“HCI”, 20)
{
}

 

public Person(string name, int age)
{
this.name = name;
this.age = age;
}

 

protected string GetName() // 파생클래스에 상속 안됨
{
return name;
}

 

protected void SetName(string name) // 파생클래스에 상속 안됨
{
this.name = name;
}

 

public void Print()
{
Console.WriteLine(“Person Name: {0} Age: {1}”, name, age);
}
}

 

class Student : Person
{
int id;
public Student() // public Student : base()와 같은 의미, 생성자는 상속안됨
{
id = 5208;
}
public Student(string name, int age, int id) : base(name, age)
{
this.id = id;
}
public void Print()
{
Console.WriteLine(“Student Name: {0} Age: {1} Id: {2}”, GetName(), age, id);
}
}

 

class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Print();
Person p1 = new Person(“HCI2~~~~~~~~~~”, 2013);
p1.Print();

Student s = new Student();
s.Print();
Student s1 = new Student(“학생들~~”, 24, 555);
s1.Print();
}
}