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

Car*_*ang 1 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?
    }
Run Code Online (Sandbox Code Playgroud)

在任何这些情况下,"f"都不会改变.如何让Union或Concat发生?

Sel*_*enç 9

UnionConcat返回一个新的, IEnumerable<T>你需要将其分配回来:

f = f.Union(g).ToList(); // since the type is IList<FileInfo>
Run Code Online (Sandbox Code Playgroud)

  • @Noob这已经在这个答案中了.去睡一会.:) (2认同)