简体   繁体   English

Linq返回类型转换

[英]Linq return type conversion

I have a linq query as follows, 我有一个linq查询,如下所示:

    var result =
                    from Record in DBContext.GetAll().
                    group new { Record.Filed1, Record.Field2} by Record.Field3
                        into newGroup
                        select new
                        {
                            BodyRegion = newGroup.Key,
                            ByScanner =
                                from exam in newGroup
                                group exam.MaxValue by exam.Model
                                    into myGroup
                                    select myGroup,

                            ByExam =
                                from exam in newGroup
                                group exam.MaxValue by exam.Protocol
                                    into myGroup2
                                    select myGroup2
};

Then I iterate throught them, 然后我遍历他们,

 foreach (var rec in result)
            { 
                foreach (var byScanner in rec.ByScanner)
                  {
                     ProcessResult(byScanner.Key, byScanner.ToList());
                  }
                foreach (var byExam in rec.ByExam )
                  {
                     ProcessResult(byExam.Key, byExam.ToList());
                  }
            }

Everything works fine. 一切正常。 But Iwant to move Linq query (first code snippet) to a function, what should be the return type the function? 但是我想将Linq查询(第一个代码段)移到一个函数中,该函数的返回类型应该是什么? Return type of a function can not be var . 函数的返回类型不能为var If I give IEnumerable< Object > then while iterating I can't access rec.ByScanner, rec.ByExam because Object doesn't contain them. 如果我给IEnumerable <Object>,则在迭代时无法访问rec.ByScanner,rec.ByExam,因为Object不包含它们。 How to resolve this issue? 如何解决这个问题?

EDIT: I tried by creating a new class and filling them in that. 编辑:我尝试通过创建一个新类并在其中填充它们。 But Grouping attributes byScanner. 但是通过Scanner对属性进行分组。 Key , byScanner. 密钥 ,byScanner。 ToList() are not accessible. ToList()无法访问。 How this can be solved? 如何解决?

You are using an Anonymous Type . 您正在使用匿名类型 These shouldn't be passed around methods. 这些不应在方法周围传递。

One thing you can do is create (Let's call it 'Record') a class with properties BodyRegion , ByScanner and ByExam and pass IEnumerable<Record> . 您可以做的一件事是创建一个具有属性BodyRegionByScannerByExam的类(我们称之为“ Record”),并传递IEnumerable<Record>

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

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