Can I do this with LINQ?

Is it possible to do this with LINQ:

1. Ensure that each item in IEnumerable<string>has the correct extension. If not, throw an exception.

foreach(var filepath in filepaths)
    if(Path.GetExtension(filepath) != @".xml")
        throw new ArgumentException(...);


2. Take IEnumerable<string>and serialize all its elements into one stringwith spaces between them.
string args = "";
foreach (var filepath in filepaths)
    args += filepath + " ";

thank

+3
source share
2 answers
if (!filepaths.All(x => Path.GetExtension(x) == @".xml"))
{
  throw error;
}

string.Join(" ", filepaths.ToArray()) for the second question.

+8
source

1.

if(filePaths.Any(filepath => Path.GetExtension(filepath) != @".xml"))
     throw new ArgumentException(...);

2.

string args = string.Join(" ", filePaths.ToArray());

or, with LINQ (much more inefficient):

string args = filePaths.Aggregate("", (combined, path) => combined + " " + path);
+5
source

Source: https://habr.com/ru/post/1769321/


All Articles