0

I want to retrieve a list of array from XML file. I use an integration tool for querying. But what should I do if I want to create a list of arrays without any foreach loop. (Reason is, in this case foreach cannot be applied.

XML File Format:

<arr name="ArrayinXML"><str>dsfadasfsdasda</str><str>gdhsdhshhfb</str>

In Index.cshtml:

@p.ArrayinXML.FirstOrDefault()

In the above case, it returns only the first string value and not the second one.

1 Answers1

0

Can you make an extension method that does the foreach for you?

Something like this:

public static class IEnumerableExtensions
{
    public static string ToString<T>(this IEnumerable<T> collection, string separater)
    {
        if (collection == null)
            return String.Empty;

        return String.Join(separater, collection);
    }
}

You could, of course, just call @String.Join(p.ArrayinXML, ", ") in your code, but I think the extension method makes it a bit more elegant.

Then add the extension namespace to your web.config, and you can do this in the view:

@p.ArrayinXML.ToString(", ")

Edit:

Here's the extension with a transform parameter so you can customize further:

public static string ToString<T>(this IEnumerable<T> collection, string separater, Func<T, object> transform) where T : class
{
    if (collection == null)
        return String.Empty;

    return String.Join(separater, collection.Select(s => transform(s).ToString()));
}
Leniency
  • 4,984
  • 28
  • 36
  • Where should i add the IEnumerableExtensions? In *Global.asax* or *Web.Config*? Because, `@String.Join(p.ArrayinXML, ",")` is not working. –  Oct 18 '11 at 15:46
  • Just added an extra extension method with a transform. @String.Join(p.ArrayinXML, ",") might not work depending on what exactly ArrayinXML is - you never showed what that object looks like. Is a collection of strings? A collection of objects? How it formats depends on how the element runs .ToString(). As for where to add the extensions, it's just an extension class, add it anywhere. Then, reference the namespace in the base web.config and in your Views/web.config file. See here: http://stackoverflow.com/questions/3239006/how-to-import-a-namespace-in-razor-view-page/6723046#6723046 – Leniency Oct 18 '11 at 16:06