Search code examples
c#linqfileopendialog

LINQ: sequence contains no elements


i have error sequence contains no element on below line

Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
            dialog.Multiselect = true;
            dialog.Filter =
                loaders
                .Select(loader => string.Format("{0}|{1}", loader.Metadata.Alias, loader.Metadata.ExtensionFilter))
                .Aggregate((f1, f2) => f1 + "|" + f2);
            dialog.Filter += "|All Files|*.*";

Solution

  • The overload of Enumerable.Aggregate you're using will throw an exception if the sequence contains no elements. You can use the overload that takes a 'seed' argument: this will just return the seed if there are no elements.

    loaders
        .Select(loader => string.Format("{0}|{1}", loader.Metadata.Alias, loader.Metadata.ExtensionFilter))
        .Aggregate(string.Empty, (f1, f2) => f1 + "|" + f2);
    

    Better still would be to ditch aggregate altogether - you're potentially allocating lots of strings you're throwing away before you get to your result. Just use string.Join:

    var loaderFilters = loaders.Select(loader 
         => string.Format("{0}|{1}", loader.Metadata.Alias, loader.Metadata.ExtensionFilter));
    
    var allFilters = loaderFilters.Concat(new []{"All Files|*.*"});
    
    dialog.Filter = string.Join("|", allFilters);