为什么我不能让这些扩展工作?

时间:2014-07-19 08:34:15

标签: c# linq extension-methods

我似乎无法获得IList.Union<>或IList.Concat<>做任何事。

这是代码。为什么这会失败?

    private void Form1_Load(object sender, EventArgs e)
    {
        DirectoryInfo C = new DirectoryInfo(@"c:\");   // 5 files here
        IList<FileInfo> f = C.GetFiles();
        int a = f.Count;
        DirectoryInfo D = new DirectoryInfo(@"c:\newfolder"); // 2 files here
        IList<FileInfo> g = D.GetFiles();
        int b = g.Count;
        f.Union(g);
        int c = f.Count;  // f remains at 5.  Why are these not unioning?
        f.Concat(g);
        int d = f.Count;   // f remains at 5. Why are these not concating?
    }

“f”在任何这些情况下都不会改变。如何让Union或Concat发生?

1 个答案:

答案 0 :(得分:9)

UnionConcat会返回您需要重新分配的新IEnumerable<T>

f = f.Union(g).ToList(); // since the type is IList<FileInfo>