使用LINQ感想

  • 4162
  • 0
  • C#
  • 2009-03-15

摘要:使用LINQ感想

最近做LINQ語法的練習,拿舊程式來改寫,發現原本使用迴圈的程式改用LINQ之後縮短了不少,

像:

XmlElement root = doc.DocumentElement;

 

XmlElement copy = doc.CreateElement("副本");

foreach (string name in m_Copy)

{

    XmlElement copyName = doc.CreateElement("全銜");

copyName.InnerText = name;

    copy.AppendChild(copyName);

}

 

root.AppendChild(copy);

改寫後:

var copyNames = from name in m_Copy

    select new XElement("全銜", name);

 

return new XElement("副本", copyNames.ToArray());

這樣大幅地減少所需的程式行數,也使得程式碼容易一目瞭然。

不過也碰到了感覺使用LINQ之後並沒有得到好處的程式,

List<XElement> result = new List<XElement>();

 

foreach (ListDocument l in section)

{

    XElement list = new XElement("條列", new XAttribute("序號", l.Name),

    new XElement("文字", l.Content));

 

    if (l.Count > 0)

       list.Add(ProcessList(l));

 

    result.Add(list);

}

 

return result.ToArray();

 這段程式以LINQ改寫後,

Func<ListDocument, XElement> method = ld => {

    XElement list = new XElement("條列", new XAttribute("序號", ld.Name),

        new XElement("文字", ld.Content));

 

if (ld.Count > 0)

           list.Add(ProcessList(ld));

        return list;

};

 

return (

    from l in section

    select method(l)).ToArray();

並沒有使程式碼容易讀懂的感覺,以自己的個性來說,是屬於喜新厭舊的類型,會偏向新的寫法,

不過在這裡,反而偏向使用舊式的寫法來進行,畢竟,這樣會比較容易讀懂。

新的語法,像LINQ這樣的新功能通常都會帶來一些便利的功能,不過,如何使用才是最大的課題,

使用得不好,這東西將成為最大的包袱,使用得好,就是最大的助力,因此,對於新技術,我覺得必須去理解,

思考、判斷如何去使用,這樣才能在最適當的位置去使用適當的技術。