C# 对泛型查找进行迭代

C# 对泛型查找进行迭代,c#,generics,collections,C#,Generics,Collections,我想向对象传递一个通用的查找。在这个对象中,我希望在访问特定属性时迭代泛型查找。我该怎么做 另一种方法对我来说也可以。我有Enumerable,我必须按任何属性对其进行分组(这就是为什么我选择了Lookup)。在目标对象中,我必须对该集合按组进行迭代,然后对每个组进行迭代,选择类型的特定属性 class Record { public DateTime RecordDate {get; set;} public string Info1 {get; set;} publi

我想向对象传递一个通用的
查找
。在这个对象中,我希望在访问特定属性时迭代泛型查找。我该怎么做

另一种方法对我来说也可以。我有
Enumerable
,我必须按任何属性对其进行分组(这就是为什么我选择了
Lookup
)。在目标对象中,我必须对该集合按组进行迭代,然后对每个组进行迭代,选择
类型
的特定属性

class Record
{
    public DateTime RecordDate {get; set;}
    public string Info1 {get; set;}
    public string Info2 {get; set;}
}

class TargetObject<type1, type2>
{
    public Lookup<type1, type2> myLookup;
    public TargetObject(Lookup<type1, type2> lookup)
    {
        myLookup = lookup;
    }

    public void TestFunc()
    {
        foreach(var item in myLookup)
        {
            var x = item.Key;
            foreach(var subItem in item)
            {
                var y = subItem. //here i like to acces type2-specific properties like Record.Info2 in a generic way
            }
        }
    }
}

List<Record> records = new List<Record>();
Lookup<DateTime, Record> lookup = records.ToLookup(r => r.RecordDate);

var target = new TargetObject(lookup);
课堂记录
{
公共日期时间记录日期{get;set;}
公共字符串Info1{get;set;}
公共字符串Info2{get;set;}
}
类TargetObject
{
公共查找myLookup;
公共目标对象(查找)
{
myLookup=查找;
}
public void TestFunc()
{
foreach(myLookup中的var项目)
{
var x=项.Key;
foreach(项目中的var子项目)
{
var y=子项//这里我想以一种通用的方式访问类型2特定的属性,如Record.Info2
}
}
}
}
列表记录=新列表();
Lookup=records.ToLookup(r=>r.RecordDate);
var目标=新目标对象(查找);
//在这里,我喜欢以一种通用的方式访问类型2特定的属性,如Record.Info2

问题是,如果你是真正的泛型,你不知道这些属性是什么。就这一点而言,我们也没有。您希望如何处理这些数据?看来你不会事先知道答案

但是有个好消息。。。这使它成为委托的完美用例

public void TestFunc(Action<type1, type2> doSomething)
{
    foreach(var item in myLookup)
    {
        var x = item.Key;
        foreach(var subItem in item)
        {
            doSomething(x, subItem);
        }
    }
}

这一行应该是固定的
var x=item.key
key属性从大写字母开始,
key
@PavelAnikhouski谢谢。您可以使用约束来指定
type2
应该实现一个公开所需属性的接口。尽管在这一点上,您也可以指定该类型,而不是使用泛型。或者,让一名代表进来也有意义。您打算对该值做什么?@juharr我将检查约束在这种情况下是否有效。指定类型对我不起作用,因为我必须将该类与几个不同的类型一起使用,这是一种有趣的方法。我试试看。乍一看,这可能对我有用。
var target = new TargetObject(lookup);
target.TestFunc((x, y) => {
    // x is the key
    // y is the subitem
    // Whatever code you put here will run once for every subitem.
    // And you will be able to use properties and methods of y.
    // As a bonus, you also have access to variables in outer scope via closures.
});