简体   繁体   English

迭代通用查找

[英]Iterate over a generic Lookup

I want to pass a generic Lookup<type1, type2> to an object.我想将通用Lookup<type1, type2>传递给对象。 In this object I want to iterate over the generic lookup while accessing specific properties.在这个对象中,我想在访问特定属性时迭代通用查找。 How Can I do this?我怎样才能做到这一点?

A different approach would also be ok for me.一种不同的方法对我来说也可以。 I have Enumerable<type> which I have to group by any property (thats why I've choosen Lookup ).我有Enumerable<type> ,我必须按任何属性对其进行分组(这就是我选择Lookup )。 In the target Object I have to iterate group-wise over this collection and then iterate over each group, picking specific properties of type .在目标对象中,我必须在这个集合上按组迭代,然后在每个组上迭代,选择type特定属性。

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);

//here i like to acces type2-specific properties like Record.Info2 in a generic way //这里我喜欢以通用方式访问类型2特定的属性,如Record.Info2

The problem is, if you're truly generic, you don't know what those properties are.问题是,如果你真的很通用,你不知道这些属性是什么。 For that matter, neither do we.就此而言,我们也没有。 What do you want to do this data?你想用这些数据做什么? It seems like you won't know that answer up front.看起来你不会预先知道那个答案。

But there's good news... that makes this the perfect use case for a delegate!但是有个好消息……这使它成为委托的完美用例!

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

And now you'd call it with a lambda, like this:现在你可以用一个 lambda 来调用它,就像这样:

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.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM