如何从模型中获取值和计数?

时间:2016-03-14 14:28:42

标签: c# asp.net

我希望能够从我创建的任何模型中获取值和数量。

例如,让我说我的模型看起来像这样。

public class test
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

我希望能够编写将查看模型的代码,然后获取ID,Name,Address并将它们放入数组中。而且我不想要这些价值观。但是来自模型的价值观。不是数据。以及获取值的计数。 3。

3 个答案:

答案 0 :(得分:2)

编辑:根据您在评论中的澄清

您可以使用反射将属性名称提取到列表中

var foo = new test();
IList<string> properties = foo.GetType().GetProperties()
    .Select(p => p.Name).ToList();

老答案

尝试将您的对象转换为NameValueCollection(https://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection(v=vs.110).aspx)。此集合提供计数,并允许您对值进行哈希表访问。您还可以为值(或键)检索IEnumerable以满足您的需求。

var foo = new test();

NameValueCollection formFields = new NameValueCollection();
foo.GetType().GetProperties()
    .ToList()
    .ForEach(pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));

注意:如果.ToString()过于具有破坏性,您可以将NameValueCollection与您选择的IDictionary实施方案进行交换。

从此问题修改的代码:how to convert an instance of an anonymous type to a NameValueCollection

答案 1 :(得分:0)

在另一堂课中,只需致电test.ID = identification; identification是您希望ID从中获取值的变量。 test是您的班级名称。

答案 2 :(得分:0)

我相信你正在寻找这样的东西(包含在示例代码中)。

class Program
{
    public class Test
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

    static void Main(string[] args)
    {
        var propertyInfo = typeof(Test).GetProperties();
        var propertyCount = propertyInfo.Count();

        Console.WriteLine($"Property count is {propertyCount}");
        foreach (var info in propertyInfo)
        {
            Console.WriteLine($"Property Name: {info.Name}");
        }

        Console.ReadKey();
    }
}

哪会给你输出:

Code Output

这允许您获取类的属性计数和属性名称。