光看文字說明很難理解IEnumerable<T>、yield break、yield return的使用方式,這裡紀錄相關程式碼範例和單元測試,幫助理解與記憶

ForeachSortedSet.jpg

//利用指定分隔符號分隔字串(輸入空白字串則不處理),再按原來順序回傳
static IEnumerable<string> SplitWithoutWhiteSpace(this string obj, params char[] separator)
{
    if (string.IsNullOrWhiteSpace(obj))
    {
        yield break;
    }

    foreach (string cell in obj.Split(separator))
    {
        yield return cell;
    }
}

//利用指定分隔符號去掉重複字串,再排序後依序回傳
static IEnumerable<string> ForeachSortedSet(this string obj, params char[] separator)
{
    if (string.IsNullOrWhiteSpace(obj))
    {
        yield break;
    }

    foreach (string cell in new SortedSet<string>(obj.Split(separator)))
    {
        yield return cell;
    }
}

//利用指定分隔符號去掉重複字串,再排序並串連成為不重複字串
static string JoinSortedSet(this string obj, in char joinSeparator, params char[] setSeparator)
{
    return setSeparator.Length <= 0 ? string.Join(joinSeparator.ToString(), obj.ForeachSortedSet(joinSeparator)) : string.Join(joinSeparator.ToString(), obj.ForeachSortedSet(setSeparator));
}

單元測試:
"".JoinSortedSet(','); //空字串
""
" ".JoinSortedSet(','); //1個空白
""
"  ".JoinSortedSet(','); //2個空白
""
"1".JoinSortedSet(',');
"1"
" 1 ".JoinSortedSet(',');
" 1 "
" 1 , 2 ".JoinSortedSet(',');
" 1 , 2 "
" 2, 1 , 2 ".JoinSortedSet(','); //排序測試
" 1 , 2, 2 "
" 2 , 1 , 2 ".JoinSortedSet(','); //排序及不重複測試
" 1 , 2 "
" 3 , 2 , 1 , 2 ".JoinSortedSet(','); //排序及不重複測試
" 1 , 2 , 3 "
" 3 , 2 , 1 , 3 , 2 ".JoinSortedSet(','); //排序及不重複測試
" 1 , 2 , 3 "

單元測試正常

實務上有其他字串處理需求時,也能再調整或擴充SplitWithoutWhiteSpace、ForeachSortedSet、JoinSortedSet

arrow
arrow
    文章標籤
    程式設計 C# UnitTest
    全站熱搜
    創作者介紹
    創作者 Yang 的頭像
    Yang

    GNAySolution

    Yang 發表在 痞客邦 留言(0) 人氣()