首页 \ 问答 \ 如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)

如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)

我有一个名为retVal的var变量,它等于某个查询。 在某些条件之后,我想将它等同于另一个查询。 但我得到一个错误,如implicit cast of type "System.Collections.Generic.IEnumerable<AnonymousType#1>" in "System.Collections.Generic.IEnumerable<AnonymousType#2>" is impossible 。 你可以问我为什么我不想定义另一个var变量。 因为这个用于foreach循环。 我们来看看代码:

var retVal = from groupItem in result.AsEnumerable()
                             where groupItem.Sms.First().amountOfParts == (
                               (from item in rawSmsList.AsEnumerable()
                                where item.referenceNumber == groupItem.Sms.First().referenceNumber
                                select item).Count()
                             )
                             select new
                             {
                                 Value = groupItem.Value,
                                 Sms = groupItem.Sms
                             };
                //CONDITION
                if (retVal.ToArray().Length==0)
                {
                    //HERE I NEED TO RETVAL EQUATE NEW QUERY
                    retVal = from groupItem in result.AsEnumerable()
                                 where groupItem.Sms.First().amountOfParts == (
                                   (from item in rawSmsList.AsEnumerable()
                                    where item.senderNumber == groupItem.Sms.First().senderNumber
                                    select item).Count()
                                 )
                                 select new
                                 {
                                     Value = groupItem.Value,
                                     Sms = groupItem.Sms
                                 };                        
                }

                foreach (var item in retVal)//FOREACH EXPECTS THE SAME RETVAL!!!

那么如何将不同的查询转换为相同的var变量? 或者如何找到var变量的类型然后将其转换为新定义的变量?


I have varvariable called retVal which equals to some query. After some conditions I want to equate it to another query. But I get an error like implicit cast of type "System.Collections.Generic.IEnumerable<AnonymousType#1>" in "System.Collections.Generic.IEnumerable<AnonymousType#2>" is impossible. You can ask me why I don't want to define another var variable. Because this one is used in foreach cycle. Let's have a look on the code:

var retVal = from groupItem in result.AsEnumerable()
                             where groupItem.Sms.First().amountOfParts == (
                               (from item in rawSmsList.AsEnumerable()
                                where item.referenceNumber == groupItem.Sms.First().referenceNumber
                                select item).Count()
                             )
                             select new
                             {
                                 Value = groupItem.Value,
                                 Sms = groupItem.Sms
                             };
                //CONDITION
                if (retVal.ToArray().Length==0)
                {
                    //HERE I NEED TO RETVAL EQUATE NEW QUERY
                    retVal = from groupItem in result.AsEnumerable()
                                 where groupItem.Sms.First().amountOfParts == (
                                   (from item in rawSmsList.AsEnumerable()
                                    where item.senderNumber == groupItem.Sms.First().senderNumber
                                    select item).Count()
                                 )
                                 select new
                                 {
                                     Value = groupItem.Value,
                                     Sms = groupItem.Sms
                                 };                        
                }

                foreach (var item in retVal)//FOREACH EXPECTS THE SAME RETVAL!!!

So how to cast different queries to the same var variable? Or how to find type of var variable and then cast it to a new defined variable?


原文:https://stackoverflow.com/questions/15651955
更新时间:2019-12-13 07:41

最满意答案

var表示隐式类型变量,这意味着它的类型将在编译时确定,所以在你的第一次使用时它会被分配一个匿名类型,在你的第二个你试图给它分配一个不同的匿名类型,你不能这样做。

您可以修改代码以使用类而不是匿名对象,然后投射到该代码,然后您将执行您现在正在执行的操作。 您可以创建类,如:

public class MyClass 
{
   public int Value {get;set;}
   public string Sms {get;set;}
}

然后通过将select语句修改为:

var retVal = ......
             select new MyClass
               {
                  Value = groupItem.Value,
                   Sms = groupItem.Sms
               };  

var means implicitly typed variable, that means its type will be determined at compile time, So on your first usage it will be assigned an anonymous type, in your second you are trying to assign it a different anonymous type, you can't do that.

You can modify your code to use a class instead of anonymous object and then project to that, then you will be to do what you are doing now. You can create the class like:

public class MyClass 
{
   public int Value {get;set;}
   public string Sms {get;set;}
}

and then project it by modifying your select statement as:

var retVal = ......
             select new MyClass
               {
                  Value = groupItem.Value,
                   Sms = groupItem.Sms
               };  
2013-03-27

相关问答

更多

翻译git版本文档的最佳实践(Best practice for translating git versioned documents)

由于两个分支共享相同的文件(并且ja分支只添加了翻译),我建议定期将master合并到ja 。 您基本上首先将master的新更改合并到您的翻译分支中。 这应该没有问题,因为您的翻译分支不会更改原始文件。 之后,您可以使用git diff HEAD^或git show -m查看新更改并添加另一个提交翻译。 如果你想检查未翻译的提交,那么你可以做git fetch; git log -p ja..origin/master git fetch; git log -p ja..origin/mast

HTML图片没有加载?(HTML image is not loading?)

我终于解决了这个问题。 我首先在Mac预览应用程序中打开了.tiff文件。 然后我复制了文件。 我以.png格式保存了副本。 图像最终加载到网页中。 I have finally solved this problem. I first opened the .tiff file in the Mac Preview application. Then I duplicated the file. I saved the duplicate in .png format. And the ima

IIS7 / Win7 - 应用程序池突然失败(IIS7/Win7 - App Pool is failing suddenly)

我可能是你有两个应用程序/网站使用一个应用程序池,但应用程序/网站运行不同的.net版本。 情况可能不是这样,但它是我曾经遇到的唯一类似的重复问题。 Because of a bug in my Entity Framework I was getting a cyclic call into one of my relationships. This was causing a stack overflow which was reported to WebOrb as a general e

使用“悬停”触发器的AngularStrap bs-dropdown不会保持打开足够长的时间(AngularStrap bs-dropdown with the “hover” trigger doesn't stay open long enough)

这是因为当您将鼠标悬停在按钮之外时,会触发hover pseudoevent的mouseleave以关注实际的下拉列表。 相反,您可以尝试将容器提供为button本身。 例 <button type="button" class="btn btn-lg btn-primary myButton" bs-dropdown="dropdown" data-container=".myButton">Hover to toggle dropdown

使用jquery更改div上的类(change class on div with jquery)

我不完全理解,但我会采取一个裂缝: 只需将.click函数分开或将其移动到if / else {}中即可。 $(function(){ var menu = $('#menu'), pos = menu.offset(); $(window).scroll(function(){ if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){

如何获取Code First Identity生成的SQL脚本?(How to get SQL scripts generated by Code First Identity?)

DbContext类不提供生成数据库脚本的方法,但底层ObjectContet提供。 您可以通过将DbContext强制DbContext为IObjectContextAdapter来访问ObjectContext : ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; string dbScript = objectContext.CreateDatabaseScript(); The D

CSS选择器:last-of-type表现不如预期(CSS selector :last-of-type not behaving as expected)

如果保留此HTML结构,则不能使用:last-of-type 。 如果你做了后备,你可以使用nth-child ,但这是CSS3并且不受几个浏览器版本的支持,所以不是最佳的。 正如@David Thomas所说:: :last-of-type不处理这些元素的类名或属性,而是处理元素本身。 你有一个fieldset ,你已经放置了4个div,你试图删除最后一个的边框,但实际上不是最后一个,但第三个...如果你有三个div,它会工作fieldset并像这样使用它: fieldset div:last

渴望在SQLAlchemy中加载具有显式自连接和contains_eager的层次结构子级(Eager loading hierarchical children with explicit self-joins and contains_eager in SQLAlchemy)

好的,你可能在SQL中观察到的是有一个“LIMIT 1”出来。 那是因为你正在使用first() 。 我们可以比较前两个查询,包含eager和joinedload: join()+ contains_eager(): SELECT master_products_1.id AS master_products_1_id, master_products_1.pid AS master_products_1_pid, master_products.id AS master_products_id

相关文章

更多

最新问答

更多
  • jsPlumb draggable element javascript函数(jsPlumb draggable element javascript function)
  • MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)
  • 如何在同一帐户上设置“Dev repo”(在prod和团队之间)(How to set up a “Dev repo” (between the prod and the team) on the same account)
  • 如何在tcl中将eth0配置为发送方udp端口(how to configure eth0 as a sender udp port in tcl)
  • 在main方法中进行更改后传递给构造函数的TreeMap实例的行为是什么(What is the behavior of a TreeMap instance passed into a constructor following changes in main method)
  • 在这个的一些属性不同的颜色(Different color in some properties of this)
  • CURL没有返回任何内容(CURL Not returning anything)
  • MVC5注入依赖于城堡windsor的视图(MVC5 injecting dependency on a view with castle windsor)
  • CakePHP AJAX-Call:发生错误:未定义(CakePHP AJAX-Call: An error occured: undefined)
  • 如何用.aidl扩展名创建文件?(how to create a file with .aidl extension?)
  • 无法获得全尺寸动态WordPress灯箱图像显示(Cannot get full size dynamic WordPress lightbox image to display)
  • 使用Jsoup删除元素不起作用(Removing Element with Jsoup doesn't work)
  • 交叉编译ARM的MongoDB C ++驱动程序。(Cross compiling MongoDB C++ driver for ARM. Cannot find Boost Libraries)
  • ProgressDialog没有关闭(ProgressDialog not closing)
  • 单元测试DB中的JPA插入(Unit testing JPA insertion in the DB)
  • 点击谷歌服务对话框中的更新按钮(Click on update button in check google service dialog)
  • 适用于PhoneGap Build的iOS“缺少必需的57x57图标”(“Missing required 57x57 icon” for iOS on PhoneGap Build)
  • MVC ckeditor post编辑器值内联(MVC ckeditor post editor value inline)
  • Angular 2 Pipe - 无法读取未定义的属性'toString'(Angular 2 Pipe - Cannot read property 'toString' of undefined)
  • 安装引导加载程序(Installing bootloaders)
  • 用于确定最终如何包含头文件的工具(Tool to figure out how a header file is eventually being included)
  • 在将字符串转换为int [duplicate]之前检查字符串是否不是数字(Check if string is not a number before converting it to a int [duplicate])
  • 从脚本构建db2数据库以进行构建验证的工具?(Tools to build db2 database from scripts for build verification?)
  • 在偏移之后向FileOutputStream写一个数字(Write a number to FileOutputStream after an offset)
  • Javascript RegEx仅限数字(无特殊字符)(Javascript RegEx for Numbers Only (no special characters))
  • 我可以在PHP的Linux服务器上运行新的COM(“WScript.Shell”)(Can I run new COM(“WScript.Shell”) on linux servers in PHP)
  • 在Backbone.js中放置与视图不直接相关的代码(例如广告,分析等)的位置?(Where to place code not directly related to a view (such as ads, analytics etc) in Backbone.js?)
  • 适用于Mac和PC的一般开发人员必备软件综合列表[关闭](Comprehensive List of Essential Software for General Developers on Mac and PC [closed])
  • 将语言文本转换为模型(Transformation Language Text to Model)
  • 在控制器中的两个方法之间共享变量?(Sharing variables between two methods in a controller?)