LINQ 自訂功能

1 篇文章 / 0 new
author
LINQ 自訂功能
將某欄位傳回的多列資料轉成以逗點分隔的單一列
void Main()
{
    Customers.Select (c => c.Name.ToUpper())        
        .OrderBy (n => n)
        .toSingleRow()
        .Dump();
    //結果像 DICK, HARRY, JAY, MARY, TOM
 
    Customers
        .Select (c => c.Name.ToUpper())
        .Pair()
        .OrderBy (n => n)
        .Dump();
    //結果像
        //HARRY, MARY
        //TOM, DICK
}
//自訂擴充函式
public static class MyExtensions
{
    public static IEnumerable<string> toSingleRow (this IEnumerable<string> source)
    {//某欄位傳回的多列資料轉成以逗點分隔的單一列
        string firstHalf = null;
        foreach (string element in source) {
            if (firstHalf == null)
                firstHalf = element;
            else
                firstHalf += ", " + element;
        }
        yield return firstHalf;
    }
    public static IEnumerable<string> Pair (this IEnumerable<string> source)
    {//轉成成對資料,
        string firstHalf = null;
        foreach (string element in source)
        if (firstHalf == null)
            firstHalf = element;
        else
        {
            yield return firstHalf + ", " + element;
            firstHalf = null;
        }
    }
}
關鍵字: 
Free Web Hosting