2010년 5월 27일 목요일

StringCollection

원문 : StringCollection











StringCollection














StringCollection 은 문자열의 컬렉션을 나타내는 .NET Framework class Library 이다.


cf) MSDN : StringCollection





여러 문자열을 관리해야될 필요가 있을때 배열인 string[] 을 쓰거나 컬렉션으로 List<string> 을 사용하였는데 StringCollection 클래스가 있다는 것을 알게되었다. 사용방법을 알아두고 필요할 때 사용하자!








Creating StringCollection





StringCollection 객체를 생성하는 방법이다. 



StringCollection authorNames = new StringCollection();







Adding Strings





StringCollection 은 string collection 에 string 을 추가하는 방법으로 다음 3가지를 제공해 준다.





● Add


● AddRange


● Insert





Add


Add 메소드는 StringCollection 의 string collection 마지막에 string 을 추가한다.





authorNames.Add("Mahesh Chand");


authorNames.Add("Mike Gold");


authorNames.Add("Praveen Kumar");


authorNames.Add("Raj Beniwal");




AddRange


AddRagne 메소드는 StringCollection 의 string collection 에 string 배열을 추가할 때 사용한다.



string[] names = new string[]{"Mahesh Chand""Mike Gold""Praveen Kumar""Raj Beniwal"};


authorNames.AddRange(names);




Insert


Insert 메소드는 StringCollection 의 string collection 에 지정한 위치에 string 을 추가한다. 


지정한 위치 인덱스가 0 보다 작거나 StringCollection 의 아이템 개수보다 크다면 ArgumentOutOfRangeException 예외가 발생한다.






authorNames.Insert(5, "New Author");







Accessing Strings





StringCollection 저장한 string 데이터들을 읽는 방법을 알아보자. 간단하게 foreach 구문을 이용하여 읽으면 된다.



StringCollection authorNames = new StringCollection();string[] names = new string[]{"Mahesh Chand""Mike Gold""Praveen Kumar""Raj Beniwal"};


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







Removing Strings





StringCollection 은 string collection 을 삭제하기 위한 3가지 메소드를 제공해준다.





● Clear


● Remove


● RemoveAt





Clear


Clear 메소드는 StringCollection 의 모든 string 아이템을 삭제한다.



authorNames.Clear();




Remove


Remove 메소드는 지정한 문자열이 StringCollection 의 string 아이템 중 첫 번째로 발견한 아이템을 삭제한다.



authorNames.Remove("Mike Gold");




RemoveAt


RemoveAt 메소드는 StringCollection 에서 지정한 위치의 string 아이템을 삭제한다. 인덱스를 사용하는 메소들과 마찬가지로 인덱스가 0보다 작거나 유효하지 않은 인덱스일 경우 ArgumentOutOfRangeException 예외가 발생한다.



authorNames.RemoveAt(5);







Find String





StringCollection 에서 원하는 string 을 찾는 방법을 알아보자.





IndexOf


indexOf 메소드는 찾을 문자열을 메소드로 전달한다. StringCollection 에서 처음 발견한 아이템의 인덱스(zero-base)를 리턴한다. 



int authorLocation = authorNames.IndexOf("Mike Gold");Console.WriteLine("Position of Mike Gold is " + authorLocation.ToString());




Contains


Contains 메소드는 찾을 문자열을 메소드로 전달한다. StringCollection 에 해당 문자열이 존재하면 true, 존재하지 않으면 false 를 리턴한다.



if (authorNames.Contains("Mike Gold")){    Console.WriteLine("Mike Gold is at position: " + authorNames.IndexOf("Mike Gold"));}







Copy Strings





StringCollection 의 string collection 을 복사하는 방법을 알아보자. 





CopyTo


CopyTo 메소드를 사용하면 StringCollection 의 string collection 을 array 로 복사한다. CopyTo 메소드는 두개의 매개변수를 받는다. 첫 번째 매개변수는 StringCollection 의 string collection 을 복사 받을 array 이름이다. 두 번째 매개변수는 array 에서 복사를 시작할 인덱스 이다.



string[] newAuthorList = new string[authorNames.Count];


authorNames.CopyTo(newAuthorList, 0);



foreach (string name in newAuthorList)

{

    Console.WriteLine(name);

}







Count Strings





Count 프로퍼티를 이용하면 StringCollection 의 아이템의 개수를 알 수있다.



Console.WriteLine("Total items in string collection: " + authorNames.Count.ToString());







Getting Items





StringCollection 은 Collection 이기 때문에 인덱서를 사용할 수 있다. 인덱서를 사용하여 아이템을 얻을 수 있다.




int authorLocation = authorNames.IndexOf("Mike Gold");

string authorName = authorNames[authorLocation];







Complete Code





위에서 설명한 메소드들을 사용한 예제이다.




using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

using System.Collections.Specialized;





namespace StringCollectionSample

{

    class Program

    {

        static void Main(string[] args)

        {

            // Create a StringCollection object

            StringCollection authorNames = new StringCollection();



            // Add string using Add method

            authorNames.Add("Mahesh Chand");

            authorNames.Add("Mike Gold");

            authorNames.Add("Praveen Kumar");

            authorNames.Add("Raj Beniwal");



            // Add an array of string using AddRange           

            string[] names = new string[]{"Mahesh Chand""Mike Gold""Praveen Kumar""Raj Beniwal"};

            authorNames.AddRange(names);



            // Insert an string at a specified index

            authorNames.Insert(5, "New Author");



            // authorNames.Clear();

            // authorNames.Remove("Mike Gold");

            // authorNames.RemoveAt(5);



            if (authorNames.Contains("Mike Gold"))

            {

                Console.WriteLine("Mike Gold is at position: " + authorNames.IndexOf("Mike Gold"));

            }



            int authorLocation = authorNames.IndexOf("Mike Gold");

            string authorName = authorNames[authorLocation];



            Console.WriteLine("Position of Mike Gold is " + authorLocation.ToString());



            Console.WriteLine("Total items in string collection: " + authorNames.Count.ToString());



            foreach (string name in authorNames)

            {

                Console.WriteLine(name);

            }



            // Copy Collection to new Array

            string[] newAuthorList = new string[authorNames.Count];

            authorNames.CopyTo(newAuthorList, 0);



            foreach (string name in newAuthorList)

            {

                Console.WriteLine(name);

            }

            //int[] intArray = new int[] { 0, 1, 2, 3, 5, 8, 13 };

            //foreach (int i in intArray)

            //{

            //    System.Console.WriteLine(i);

            //}



            Console.ReadLine();





        }

    }

}















cf)


원문 포스트를 읽다보니 리플로 StringCollection 은 전혀 새롭게 추가된 것도 아니며 List<string> 을 사용하는게 더 쉽다고 남겨져 있다. 원문 작성자는 개발자가 List<>를 잘 모를 경우 StringCollection 을 사용하는게 시간 절약이라고 말하고 있다. 음.. List 컬렉션에 익숙해 지는게 더 이익인것 같다.

2010년 5월 23일 일요일

C# Join String Method

원문 : C# Join String Method







C# Join String Method


C# 을 사용하면서 문자열을 결합할 때 많은 방법이 있을 수 있지만 String.Join 정적 메소드를 이용하면 편리하게 문자열을 결합할 수 있다. 문자열을 결할할 때 문자열과 문자열 사이의 구분 문자를 임의로 정할 수 있다.

문자열을 결합하는 방법으로 StringBuilder 클래스를 이용하는 방법도 있는데 String.Join 메소드를 사용하는 방법이 더 퍼로먼스가 좋다고 한다. (직접 확인해 보지는 못했지만..)




Using string.Join

string.Join 메소드는 array 또는 List 컬렉션을 이용하여 구분 문자로 구분된 결합된 문자열을 string 객체로 반환한다.


using System;

namespace StringJoin
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            string[] arr = { "one", "two", "three" };

            Console.WriteLine(string.Join(",", arr)); // "string" can be lowercase, or
            Console.WriteLine(String.Join(",", arr)); // "String" can be uppercase            
        }
    }
}




원문 포스트의 예제를 그대로 코딩해보았다. 출력 결과를 보니 구분자를 이용하여 잘 결합된 문자열을 얻었다.
주석에 보면 string.Join 과 String.Join 이 있는데 둘의 차이점은 다들 알고 있겠지?!
String 은 BCL 이고 string 은 C# 에서 String 에 별칭을 부여한 것이다. C# 에서 별칭된 것이 있다면 그것을 사용하라고 배운 것 같다.


How string.Join is different from appending
string.Join 은 appending 과 어떻게 다를까??
string.Join 은 문자열과 문자열을 결합할 때 구분 문자를 문자열 사이에만 삽입하는데 반해, StringBuilder 의 appending 메소드는 문자열과 문자열 사이 뿐만 아니라 마지막 문자열 끝에도 구분 문자를 삽입한다. 이건 기본적인 동작이 그렇다기 보다 appending 으로 간단하게 문자열을 결합할 때 그렇게 된다는 소리다. 따라서 마지막에 추가된 구분 문자를 제거하는 코드를 따로 넣어 주게 된다.


internal class Program
{
        static void Main()
        {
            string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" };
            Console.WriteLine(CombineA(catSpecies));
            Console.WriteLine(CombineB(catSpecies));
        }

        /// <summary>
        /// Combine strings with commas.
        /// </summary>
        static string CombineA(string[] arr)
        {
            return string.Join(",", arr);
        }

        /// <summary>
        /// Combine strings with commas.
        /// </summary>
        static string CombineB(string[] arr)
        {
            StringBuilder builder = new StringBuilder();
            foreach (string s in arr)
            {
                builder.Append(s).Append(",");
            }
            return builder.ToString().TrimEnd(new char[] { ',' });
        }
    }




string.Join 메소드를 사용한 코드는 이제 익숙하고.. 만약 StringBuilder 의 Appending 으로 문자열을 결합한다면 위와 같은 코드를 사용하게 된다. 반복문에서 구분 문자열을 더하기 때문에 마지막에 추가된 구분 문자를 제거한다. 보이는 것과 같이 string.Join 메소드를 사용하는게 코드도 깔끔하다.


string.Join exception
string.Join 메소드에서 발생할 수 있는 예외는 3가지 이다.



ArgumentNullException
ArgumentOutOfRangeException
OutOfMemoryException

처음 두개의 예외는 코딩하면서 발생할 가능성이 많으므로 예외 처리를 해두어야 한다.


Using string.Join on List
실제 업무에서 string[] 보다는 List<string> 컬렉션을 자주 사용하게 된다.


static void Main()
{
        // List of cities
        List<string> cities = new List<string>();
        cities.Add("New York");
        cities.Add("Mumbai");
        cities.Add("Berlin");
        cities.Add("Istanbul");

        // Join strings into one CSV line
        string line = string.Join(",", cities.ToArray());
        Console.WriteLine(line);
}



cf) C# 4.0 에서는 string.Join 메소드가 List 컬렉션 자체를 파라미터로 받을 수 있게 string.Join<string> 정적 메소드가 존재한다고 한다. C# 4.0 기술 들도 이제 슬슬 블로그에서 보인다..
C# Join String List



2010년 5월 15일 토요일

C# List CopyTo Method

출처 : C# List CopyTo Method




C# List CopyTo Method


하나의 List Collection 이 있다. 이 데이터를 배열에 복사하고 싶을 List Collection 의 CopyToMethod 메소드를 사용하면 된다.
사용 상 특징적인 것은

1. 1차원 배열에 복사한다.
2. 이때 복사는 Shallow copy 가 아니라 Deep copy 로 복사한다.
3. 복사 대상인 List Collection 의 데이터 개수가 복사 할 곳인 배열의 크기가 작으면 안된다.


예제에서는 CopyToMethod 의 동작과 Shallow copy 인지 Deep Copy 인지 테스트 해 보았다.

namespace CopyToDemo
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var list = new List<int>() { 5, 6, 7 };
            int[] array = new int[list.Count];
            list.CopyTo(array);

            Console.WriteLine(array[0]);
            Console.WriteLine(array[1]);
            Console.WriteLine(array[2]);

            Console.WriteLine(Environment.NewLine);
            array[0] = 1;
            array[1] = 2;
            array[2] = 3;
            Console.WriteLine(array[0]);
            Console.WriteLine(array[1]);
            Console.WriteLine(array[2]);

            Console.WriteLine(Environment.NewLine);
            foreach (int n in list)
            {
                Console.WriteLine(n);
            }
        }
    }
}


출력 결과




음... 아직 사용해 보지 못하였지만 이제 알았으니 필요할 때 기억할 수 있었으면 한다.



2010년 5월 14일 금요일

C# string.IsNullOrWhiteSpace Method

C# string.IsNullOrWhiteSpace Method


우선 .NET 3.5 버전에 추가되었는지 아니면 그 전에 추가된 것 인지는 모르지만 String 타입에 IsNullOrEmpty 라는 정적 메소드가 있다. 위 블로그에 가보니까 IsNullOrWhiteSpace 정적 메소드가 있길래 "아!! 저런게 있었구나!!" 했다.
But, 읽어보니 .NET 4.0 에서 추가된 확장 메소드 같다. 아닌가?! Visual Studio 2010 나올 때 .NET 4.0 도 나온다던데 그 때 확인해 봐야겠다.


.NET 4.0 에서 IsNullOrWhiteSpace 의 구현 예상(?) 코드


public static bool IsNullOrWhiteSpace(string value)
{
    if (value != null)
    {
        for (int i = 0; i < value.Length; i++)
        {
            if (!char.IsWhiteSpace(value[i]))
            {
                return false;
            }
        }
    }
    return true;
}



사용 예


using System;

class Program
{
    static void Main()
    {
        bool a = string.IsNullOrWhiteSpace("   ");
        bool b = string.IsNullOrWhiteSpace("\n");
        bool c = string.IsNullOrWhiteSpace("\r\n\v ");
        bool d = string.IsNullOrWhiteSpace(null);
        bool e = string.IsNullOrWhiteSpace("");
        bool f = string.IsNullOrWhiteSpace(string.Empty);
        bool g = string.IsNullOrWhiteSpace("dotnetperls");
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
        Console.WriteLine(d);
        Console.WriteLine(e);
        Console.WriteLine(f);
        Console.WriteLine(g);
    }
}



출력 결과


True
True
True
True
True
True
False





WhiteSpace 문자는 다음과 같다.
1. "   "
2. ""
3. "\r\n\v\t" 와 같은 문자


String.IsNullOrEmpty
 

.NET Framework 3.5 String.IsNullOrEmpty 메소드의 사용 예 
bool result;

result = string.IsNullOrEmpty(null);        // true

result = string.IsNullOrEmpty("");          // true

result = string.IsNullOrEmpty(" ");         // false

result = string.IsNullOrEmpty("Test");      // false



String.IsNullOrWhiteSpace

.NET Framework 4.0 에 포함된 String.IsNullOrWhiteSpace
bool result;

result = string.IsNullOrWhiteSpace(null);   // true

result = string.IsNullOrWhiteSpace("");     // true

result = string.IsNullOrWhiteSpace(" ");    // true

result = string.IsNullOrWhiteSpace("\t");   // true

result = string.IsNullOrWhiteSpace("Test"); // false




참조
C# string.IsNullOrWhiteSpace Method
- String.IsNullOrWhiteSpace

2010년 5월 5일 수요일

C# DateTime.TryParseExact Method

출처 : http://dotnetperls.com/datetime-tryparseexact


C# DateTime.TryParseExact Method




DateTime 클래스의 정적 메소드로 TryParseExact 가 있다. 어디에 쓰는건가 하니... 시간, 날짜 정보가 포함된 string 타입의 문자열이 있을 때, 분명히 시간 정보이긴 하나 string 문자열일 뿐이므로 DB에 저장, DateTimePicker 등 과 같은 곳에 사용하기가 무척 까다롭다. 이 문자열을 DateTime.TryParseExact 메소드를 사용하면 DateTime 변수로 변경할 수 있다.


using System;
using System.Globalization;

namespace DateTimeTryParseExact
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            string dateString = "Mon 16 Jun 8:30 AM 2008";
            string format = "ddd dd MMM h:mm tt yyyy";
            DateTime dateTime;

            if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
                                       DateTimeStyles.None, out dateTime))           
                Console.WriteLine(dateTime);           
        }
    }
}




TryParseExact 메소드는 format string(위 예제에서 format 변수 값) 을 사용하여 DateTime 형 변수로 변환시켜 준다.
DateTime.TryParse 메소드도 존재하지만 DateTime.TryParseExact 메소드가 성능이 향상되었고 코드를 더 간단하게 한다.

format string 을 잘 못 지정해 주거나, 시간/날짜 정보를 포함한 문자열이 올바르지 않을 경우 DateTime.TryParseExact 메소드는 false 를 리턴한다.



using System;
using System.Globalization;

namespace DateTimeTryParseExact
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            string dateString = "???";
            string format = "ddd dd MMM h:mm tt yyyy";

            DateTime dateTime;
            if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
                                       DateTimeStyles.None, out dateTime))           
                Console.WriteLine(dateTime);           
        }
    }
}



얼마전 DB로 부터 시간 정보를 string 으로 타입으로 얻어왔는데 이 값을 DateTimePicker 컨트롤에 넣으려다 참 난감해 했던적이 있다. 이게 도움이 될려나... 아하하하하하