如何使用LINQ返回的变量? [英] How to use returned linq variable?
问题描述
我决定来快速浏览一下事物的LINQ方面,由于只使用直线上升foreach循环反对,但我有一些麻烦它的工作,主要是由于数据类型,我相信。
I've decided to take a quick look into the LINQ side of things, as opposed to just using a straight up foreach loop, but i'm having some trouble getting it to work, mainly due to datatypes i believe.
所以,我这有,到目前为止;
So i've got this, so far;
var selectedSiteType = from sites in siteTypeList
where sites.SiteTypeID == temp
select sites;
siteTypeList是SiteTypes的列表。我试图找到一个特定的一个(我已经谴责与变量温度。
siteTypeList is a list of SiteTypes. I'm trying to find a particular one (Which i've denounced with variable "temp".
我如何再使用这个选择SiteType AS一SiteType?当我尝试,并通过传递selectedSiteType到其他功能,像这样;
How do i then use this selected SiteType AS a SiteType? When i try and pass "selectedSiteType" through to another function, like so;
mSiteTypeSub.EditSitetype(selectedSiteType);
请注意:我试着用提供索引,仿佛selectedSiteType是一个列表/阵列,但没有工作要么,我得到以下错误:
note: I tried with providing an index, as if selectedSiteType was a list / Array, but that didnt work either, i get the following error:
Argument 1: cannot convert from
'System.Collections.Generic.IEnumerable<DeviceManager_take_2.SiteType>' to
'DeviceManager_take_2.SiteType'
我失去了一些东西?也许铸造某种?就像我说我是新来的这一点,我在努力让我的头围绕这一点。机会是我已经得到了整个概念错误,bingbangbosh我已经做了洋相!
Am i missing something? perhaps a cast of some kind? Like i said i'm new to this and am struggling to get my head around this. Chances are i've got the whole concept wrong and bingbangbosh i've made a fool of myself!
干杯提前。
推荐答案
使用首先 / FirstOrDefault /的Single / <一href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.singleordefault.aspx">SingleOrDefault以获得特定类型的集合的一个项目。
Use First / FirstOrDefault / Single / SingleOrDefault to get a an item of the particular type from the collection.
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.
这篇关于如何使用LINQ返回的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!