1

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|*.*";
Maverick
  • 1,396
  • 5
  • 22
  • 42

2 Answers2

3

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);
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
0

Your code can be simplified to:

Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
dialog.Multiselect = true;
dialog.Filter = string.Join("|", loaders.Select(loader => loader.Metadata.Alias + "|" + loader.Metadata.ExtensionFilter)) + "|All Files|*.*";