简体   繁体   English

LINQ:序列不包含任何元素

[英]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|*.*";

The overload of Enumerable.Aggregate you're using will throw an exception if the sequence contains no elements. 如果序列不包含任何元素,则您正在使用的Enumerable.Aggregate的重载将引发异常。 You can use the overload that takes a 'seed' argument: this will just return the seed if there are no elements. 您可以使用带有'seed'参数的重载:如果没有元素,这将仅返回种子。

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 : 只需使用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);

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|*.*";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM