2013-08-07 33 views
0

選擇我有一個類,就像下面:簡單的Linq查詢到從單個項目

public class ParentData 
{ 
    public List<ChildData> ChildDataList { get; set; } 
    public ChildData AnotherChildData { get; set; } 
} 

我要尋找一個簡單的Linq查詢,使這些2個成員的選擇。這是我實際上做的:

var query = (from data in parentData.ChildDataList select data) 
      .Union 
      (from data in new List<ChildData> { parentData.AnotherChildData } select data); 

有沒有更好的方法來做到這一點?謝謝。

+0

可能重複的[有沒有一個neater linq的方式來'聯盟'單個項目?](http://stackoverflow.com/questions/3532176/is-there-a-ne ater-linq-way-to-union-a-single-item) –

+0

確實是重複的。在發佈我之前,我沒有看到這個問題。謝謝! –

+0

如果你不使用相同的措辭,他們可能很難找到,但嘿,這是社區的目的:) 無論如何,現在這兩個問題是相互關聯的,所以任何搜索你的人都會發現鏈接的問題 –

回答

0

這裏是我(根據Is there a neater linq way to 'Union' a single item?)所使用的解決方案:

public static class LinqHelper 
{ 
    // returns an union of an enumerable and a single item 
    public static IEnumerable<T> SingleUnion<T>(this IEnumerable<T> source, T item) 
    { 
     return source.Union(Enumerable.Repeat(item, 1)); 
    } 

    // returns an union of two single items 
    public static IEnumerable<T> SingleUnion<T>(this T source, T item) 
    { 
     return Enumerable.Repeat(source, 1).SingleUnion(item); 
    } 
} 

然後,我可以這樣做:

var query = parentData.ChildDataList 
      .SingleUnion(parentData.AnotherChildData) 
+0

請確保您瞭解'Concat'和'Union'之間的區別。爲此,請閱讀我對我的回答的評論。 –

+1

是的,我明白不同之處,謝謝:) –

4

你可以減少代碼這樣:

var query = parentData.ChildDataList 
         .Concat(new [] { parentData.AnotherChildData }); 
+1

@Concat也可以在這個短代碼中使用'Union' – Matten

+3

@Matten:它們有不同的含義。 Concat只是將第二個列表追加到第一個列表中。聯盟確保結果只包含不同的項目,即它比較項目。這成本更高,結果可能會有所不同,我感覺這不是OP想要的。當他使用'Union'時,他可能會想到SQL的'UNION ALL',它是LINQ中的'Concat'。 –

+1

@DanielHilgarth:老兄,我覺得自己像個白癡。我們已經有了5年的時間了?我從來不知道'Union'返回了不同的項目。 +1,感謝隊友。 –