我决定快速浏览一下LINQ方面的内容,而不是仅仅使用一个直接的foreach循环,但我在使用它时遇到一些麻烦,主要是因为我相信数据类型.
到目前为止,我已经得到了这个;
var selectedSiteType = from sites in siteTypeList
                                   where sites.SiteTypeID == temp
                                   select sites;
siteTypeList是SiteTypes的列表.我正试图找到一个特定的(我已经用变量"temp"谴责了.
然后,我如何将此选定的SiteType AS用作SiteType?当我尝试将"selectedSiteType"传递给另一个函数时,就像这样;
mSiteTypeSub.EditSitetype(selectedSiteType);
注意:我尝试提供索引,就好像selectedSiteType是一个列表/数组,但是也没有用,我得到以下错误:
Argument 1: cannot convert from 
'System.Collections.Generic.IEnumerable<DeviceManager_take_2.SiteType>' to 
'DeviceManager_take_2.SiteType' 
我错过了什么吗?也许是某种演员?就像我说我是新手一样,我正在努力解决这个问题.机会是我有错误的整个概念和bingbangbosh我自己做了一个傻瓜!
提前干杯.
Hab*_*bib 17
使用First/FirstOrDefault/Single/SingleOrDefault从集合中获取特定类型的项目.
   var value = selectedSiteType.First(); 
   // returns the first item of the collection
   var value = selectedSiteType.FirstOrDefault(); 
   // returns the first item of the collection or null if none exists
   var value = selectedSiteType.Single(); 
   // returns the only one item of the collection, exception is thrown if more then one exists
   var value = selectedSiteType.SingleOrDefault(); 
   // returns the only item from the collection or null, if none exists. If the collection contains more than one item, an exception is thrown. 
如果您的退货类型是单一的:
   var selectedSiteType = (from sites in siteTypeList
                                       where sites.SiteTypeID == temp
                                       select sites).SingleOrDefault();
如果列表(可能有多个项目):
 var selectedSiteType = (from sites in siteTypeList
                                       where sites.SiteTypeID == temp
                                       select sites).ToList();
这是您在查询中遗漏的SingleOrDefault/ToList.