rich dvc
rich dvc

Reputation: 31

get array values using Linq (LinqPad)

I have the following array and Linq statements. I can get the field name with the Linq, but how to I retrieve the field value? (in LinqPad)

var source = new[] {
   new { FirstName = "Foo", SurName = "Bar", Password = "secret" },
};

var membersToInclude =
   source
      .First()
      .GetType()
      .GetProperties()
      .Where(x => x.Name != "Password")
      .Select(x => x.Name)
      .ToArray();

foreach (var m in membersToInclude)
{
   m.Dump();
}

The Dump() just displays the words -- FirstName, SurName -- How can I also get the values -- Foo and Bar?

While I'm at it (ok I'm asking 2 questions in one post -- but .... they are all linq --LinqPad related) how do you get string length using Linq (well, LinqPad)

 from w in Albums.Take(5)
     select new
     {
        w1 = w.AlbumArtUrl.Substring(1,5),
        w2 = w.AlbumArtUrl.Length
     }

The Substring function works fine, but when I try to get Length, LinqPad gives me this message

The specified argument value for the function is not valid. [ Argument # = 1,Name of function(if known) = LEN ]

I have tried using len, LEN, ... how to get the string length value?

Upvotes: 0

Views: 1514

Answers (1)

Vasiliy Ivashin
Vasiliy Ivashin

Reputation: 425

You're selecting just property's name. You need to apply it to an object to get the value. This should give you an idea:

var source = new[] {
   new { FirstName = "Foo", SurName = "Bar", Password = "secret" },
};

var membersToInclude =
   source
      .First()
      .GetType()
      .GetProperties()
      .Where(x => x.Name != "Password")
      .Select(x =>
          {
            var value = x.GetValue(source.First());
            return new {x.Name,  value};
          })
      .ToArray();

foreach (var m in membersToInclude)
{
   m.Dump();
}

Upvotes: 3

Related Questions