C# C语言中具有自定义集合的元素度量#

C# C语言中具有自定义集合的元素度量#,c#,C#,考虑到我需要能够在某个时候访问所有数据类的一些指标,我正试图找出组织一组数据类的最佳方法 下面是我的或类的一个片段: public enum status { CLOSED, OPEN } public class OR { public string reference { get; set; } public string title { get; set; } public status status { get; set; } } 不是每一个或我初始化将有所有

考虑到我需要能够在某个时候访问所有数据类的一些指标,我正试图找出组织一组数据类的最佳方法

下面是我的或类的一个片段:

public enum status { CLOSED, OPEN }

public class OR
{
    public string reference { get; set; }
    public string title { get; set; }
    public status status { get; set; }
}
不是每一个或我初始化将有所有属性的值。我希望能够以这样一种方式“收集”数千个这样的对象,我可以很容易地获得多少个或多少个对象有一个值集。例如:

OR a = new OR() { reference = "a" }
OR b = new OR() { reference = "b", title = "test" }
OR c = new OR() { reference = "c", title = "test", status = status.CLOSED }
List<OR> orList = ...;

int titleCount = orList
       .Where(o => ! string.IsNullOrEmpty(o.title))
       .Count(); 

Dictionary<status, int> statusCounts = orList
        .GroupBy(o => o.status)
        .ToDictionary(g => g.Key, g => g.Count());
现在,这些数据以某种方式收集,我可以这样做(伪):

我还希望能够收集枚举类型属性的度量,例如,从集合中检索一个
字典
,如下所示:

Dictionary<string, int> statusCounts = { "CLOSED", 1 }
Dictionary statusCounts={“CLOSED”,1}
想要访问这些指标的原因是,我正在构建两个OR集合,并将它们并排进行比较,以找出任何差异(它们应该是相同的)。我希望能够首先在这个更高的层次上比较它们的度量标准,然后细分它们之间的差异

感谢您提供有关如何实现此目标的任何信息。:-)

。。。“收集”成千上万的这些

数千不是一个巨大的数字。只需使用
列表
,您就可以通过Linq查询获得所有指标

例如:

OR a = new OR() { reference = "a" }
OR b = new OR() { reference = "b", title = "test" }
OR c = new OR() { reference = "c", title = "test", status = status.CLOSED }
List<OR> orList = ...;

int titleCount = orList
       .Where(o => ! string.IsNullOrEmpty(o.title))
       .Count(); 

Dictionary<status, int> statusCounts = orList
        .GroupBy(o => o.status)
        .ToDictionary(g => g.Key, g => g.Count());
列表或列表=。。。;
int titleCount=orList
.Where(o=>!string.IsNullOrEmpty(o.title))
.Count();
字典状态计数=orList
.GroupBy(o=>o.status)
.ToDictionary(g=>g.Key,g=>g.Count());

您可以使用此linq查询获取标题计数:

int titleCount = ORCollection
                    .Where(x => !string.IsNullOrWhiteSpace(x.title))
                    .Count();
您可以通过如下方式获得关闭的计数:

int closedCount = ORCollection
                     .Where(x => x.status == status.CLOSED)
                     .Count();

如果您将拥有更大的集合或经常访问这些值,那么创建一个存储字段计数的自定义集合实现可能是值得的,它可以在添加和删除项时增加/减少这些值。您还可以在此自定义集合中存储状态计数字典,该字典在添加和删除项目时会更新。

使用Linq的现有答案非常棒,非常优雅,因此下面介绍的想法仅供后人使用

这是一个(非常粗略的)基于反射的程序,它将允许您计算任何对象集合中的“有效”属性

验证器由您在验证器字典中定义,以便您可以轻松更改每个属性的有效/无效值。如果最终对象具有大量属性,并且不希望必须为每个属性在实际集合本身上编写内联linq度量,那么您可能会发现它作为一个概念很有用

您可以将其作为一个函数进行配置,然后对两个集合运行它,这样您就可以报告两者之间的确切差异,因为它会在最终的字典中记录对单个对象的引用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace reftest1
{
    public enum status { CLOSED, OPEN }

    public class OR 
    {
        public string reference { get; set; }
        public string title { get; set; }
        public status status { get; set; }
        public int foo { get; set; }

    }

    //creates a dictionary by property of objects whereby that property is a valid value
    class Program
    {

        //create dictionary containing what constitues an invalid value here
        static Dictionary<string,Func<object,bool>> Validators = new Dictionary<string, Func<object,bool>>
            {

                {"reference", 
                    (r)=> { if (r ==null) return false;
                              return !String.IsNullOrEmpty(r.ToString());}
                },
                {"title",
                    (t)=> { if (t ==null) return false;
                              return !String.IsNullOrEmpty(t.ToString());}
               }, 
               {"status", (s) =>
                    {
                        if (s == null) return false;
                        return !String.IsNullOrEmpty(s.ToString());
              }},
             {"foo",
                 (f) =>{if (f == null) return false;
                            return !(Convert.ToInt32(f.ToString()) == 0);}
                    }
            };

        static void Main(string[] args)
        {
            var collection = new List<OR>();
            collection.Add(new OR() {reference = "a",foo=1,});
            collection.Add(new OR(){reference = "b", title = "test"});
            collection.Add(new OR(){reference = "c", title = "test", status = status.CLOSED});

            Type T = typeof (OR);
            var PropertyMetrics = new Dictionary<string, List<OR>>();
            foreach (var pi in GetProperties(T))
            {
                PropertyMetrics.Add(pi.Name,new List<OR>());
                foreach (var item in collection)
                {
                    //execute validator if defined
                    if (Validators.ContainsKey(pi.Name))
                    {
                       //get actual property value and compare to valid value
                       var value = pi.GetValue(item, null);
                       //if the value is valid, record the object into the dictionary
                       if (Validators[pi.Name](value))
                       {
                           var lookup = PropertyMetrics[pi.Name];
                           lookup.Add(item);
                       }
                    }//end trygetvalue
                }
            }//end foreach pi
            foreach (var metric in PropertyMetrics)
            {
                Console.WriteLine("Property '{0}' is set in {1} objects in collection",metric.Key,metric.Value.Count);
            }
            Console.ReadLine();
        }


        private static List<PropertyInfo> GetProperties(Type T)
        {
            return T.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
运用系统反思;
命名空间reftest1
{
公共枚举状态{关闭,打开}
公共类或
{
公共字符串引用{get;set;}
公共字符串标题{get;set;}
公共状态状态{get;set;}
公共int foo{get;set;}
}
//按对象的属性创建字典,其中该属性是有效值
班级计划
{
//创建包含构成此处无效值的内容的词典
静态字典验证器=新字典
{
{“参考”,
(r) =>{if(r==null)返回false;
return!String.IsNullOrEmpty(r.ToString());}
},
{“头衔”,
(t) =>{if(t==null)返回false;
return!String.IsNullOrEmpty(t.ToString());}
}, 
{“状态”,(s)=>
{
如果(s==null)返回false;
return!String.IsNullOrEmpty(s.ToString());
}},
{“foo”,
(f) =>{if(f==null)返回false;
return!(Convert.ToInt32(f.ToString())==0;}
}
};
静态void Main(字符串[]参数)
{
var collection=新列表();
Add(new或(){reference=“a”,foo=1,});
添加(新的或(){reference=“b”,title=“test”});
添加(新建或(){reference=“c”,title=“test”,status=status.CLOSED});
类型T=类型(或);
var PropertyMetrics=新字典();
foreach(GetProperties(T)中的var pi)
{
Add(pi.Name,newlist());
foreach(集合中的var项)
{
//执行验证器(如果已定义)
if(Validators.ContainsKey(pi.Name))
{
//获取实际属性值并与有效值进行比较
var value=pi.GetValue(项,空);
//如果该值有效,请将该对象记录到字典中
if(验证器[pi.Name](值))
{
var lookup=PropertyMetrics[pi.Name];
查找。添加(项);
}
}//结束trygetvalue
}
}//每端圆周率
foreach(房地产计量中的var度量)
{
WriteLine(“在集合中的{1}对象中设置了属性“{0}”)、metric.Key、metric.Value.Count);
}
Console.ReadLine();
}
私有静态列表GetProperties(类型T)
{
返回T.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
}
}
}
绝对不需要