0

Here is my static class holding the constants

public static class Files
{
    public const string FileA = "Block1";
    public const string FileB = "Block2";
    public const string FileC = "Block3";
    public const string FileD = "Block6.Block7";
 }

By any chance, is it possible to get constants as list using LINQ other than converting it to data tables and retrieve. Thanks

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Manivannan KG
  • 371
  • 1
  • 9
  • 24

2 Answers2

2

Hope that you are looking for something like this :

List<string> staticconstList = new List<string>(); 
Type type = typeof(Files);
foreach (var field in type.GetFields())

{
    var val = field.GetValue(null);               
    staticconstList.Add(val.ToString());
}

Or something like This:

List<string> staticconstList = type.GetFields().Select(x => x.GetValue(null).ToString()).ToList();
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
2

With reflection you can go like this, the result a enumerable with a Field, Value structure.

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication2
{
    public static class Files
    {
        public const string FileA = "Block1";
        public const string FileB = "Block2";
        public const string FileC = "Block3";
        public const string FileD = "Block6.Block7";
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            var t = typeof(Files);
            var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);

            var list = fields.Select(x => new {Field = x.Name, Value = x.GetValue(null).ToString()});


            Console.Read();
        }
    }
}
hpfs
  • 486
  • 9
  • 14