There is a list

var list = new List<string>() {"12", "23", "34"}; var val1 = ""; var val2 = ""; var val3 = ""; 

How using lambda or linq to put variables from the list in val1, val2, val3. I'll do it in a loop, but I want a more elegant solution.

  • one
    in the loop? and how do you do it? - DreamChild
  • for (int i = 0; i <list.Counr (); i ++) {val + "i" = list [i]} - Radzhab
  • C # if you know a little? It will not work. It does not even compile because val + "i" is not an lvalue. - DreamChild
  • 3
    Generally, how many times there was a desire to expand the vector / list / etc into variables, so many times it turned out that in fact it is completely meaningless and not necessary :) - user6550
  • one
    @Radzhab: Very correctly, you most likely do not need it. Tell your real task: why do you need it? - VladD

1 answer 1

I can offer a solution based on DLR (.NET 4.0+):

 public static class Exts { public static dynamic ExtractIndices<T> (this IEnumerable<T> @this, string propertyPrefix) { CultureInfo culture = CultureInfo.InvariantCulture; var variables = new ExpandoObject(); var dictionary = (IDictionary<string, object>)variables; int index = 1; using (IEnumerator<T> enumerator = @this.GetEnumerator()) { while (enumerator.MoveNext()) { string propertyName = string.Format(culture, "{0}{1}", propertyPrefix, index++); dictionary[propertyName] = enumerator.Current; } } return variables; } } 

Using:

 var list = new List<string> { "12", "23", "34" }; var v = list.ExtractIndices("al"); Console.WriteLine("{0} {1} {2}", v.al1, v.al2, v.al3); 

The disadvantages include an extra point in the name of "variables", but is this a hindrance?

PS What is the question, such an answer.

  • one
    +1 for postscript. - VladD
  • one
    @VladD With foreach, the code is not terrible enough. - Athari
  • one
    Ok, accepted! [15] - VladD
  • one
    And I also like static dynamic . - VladD
  • one
    @VladD It may be worth adding new unsafe async ... - Athari