Tatranskymedved Tatranskymedved -4 years ago 143
C# Question

FileDialog filter - LINQ concatination

While creating service to display

OpenFileDialog
/
SaveFileDialog
, I was thinking about creating LINQ query/clear C# code to
Concatinate()
/
Join()
filter expression.

Do the filter based on this call:

string res = "";
if(new Service().ShowOpenFileDialog(out res,
new string[]{ "JPG", "TXT", "FBX"},
new string[]{ "Images", "TextFile", "FilmBox"}))
Console.WriteLine(res); //DisplayResult


Example definition:

public bool ShowOpenFileDialog(out string result, string[] ext, string[] desc)
{
if(ext.Length != desc.Length) return false;

OpenFileDialog diag = new OpenFileDialog();

// problematic part
// diag.Filter = "Text File (*.txt)|*.txt";
// diag.Filter = desc[0] + " (*." + ext[0] + ")|*." + ext[0];
// diag.Filter += "|"+desc[1] + " (*." + ext[1] + ")|*." + ext[1];

// I tried something like:
// diag.Filter = String.Join("|", desc.Concat(" (*." + ext[0] + ")|*." + ext[0]));
// but not sure how to pass indexes across LINQ queries

diag.Filter = /* LINQ? */

if(diag.ShowDialog() == true)
{
result = diag.FileName;
return true;
}
return false;
}


Question: Is it possible to create LINQ to concatenate/join 2 arrays in such format? Is it needed to do it by code? If so, what is the cleanest/least expensive solution?

Note: As a filter (result) example:

"Images (*.JPG)|*.JPG |TextFile (*.TXT)|*.TXT |FilmBox (*.FBX)|*.FBX"


EDIT: Also please consider there might be
n
items in the arrays.

Answer Source

You should use Select to iterate over your collection. Also, string interpolation comes in handy here.

string filter = string.Join
                       ( "|"
                       , ext.Zip
                             ( desc
                             , (e, d) => new
                                         { Ext = e
                                         , Desc = d
                                         }
                             )
                            .Select(item => $"{item.Desc} (*.{item.Ext})|*.{item.Ext}")
                       );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download