2011-09-07 103 views
26

对象数组,我想知道我怎么可以查询对象的数组。例如,我有一个像CarList这样的数组对象。所以CarList [0]会返回对象Car。汽车有属性模型和制造。现在,我想用LINQ查询数组,卡洛斯拿到车,其型号是说“宝马”的品牌。我尝试以下查询使用LINQ

var carMake = from item in CarList where item .Model == "bmw" select s.Make; 

我得到的错误

找不到源类型卡洛斯查询模式的实现[]

我不能卡洛斯从阵列更改为像列表<>因为卡洛斯被retured以我为从web服务阵列。

请让我知道这是可以解决的。如果你可以使用C#代码解释会很好。

在此先感谢。

+1

你不应该选择item.Make? –

+1

所有的,有什么理由赞成票通过两次在代码中一个错字产生一个问题吗?将s更改为item并删除空间.Model是他需要的唯一解决方案。 –

回答

52

地址:

using System.Linq; 

到文件的顶部。

然后:

Car[] carList = ... 
var carMake = 
    from item in carList 
    where item.Model == "bmw" 
    select item.Make; 

,或者您更流畅的语法:

var carMake = carList 
    .Where(item => item.Model == "bmw") 
    .Select(item => item.Make); 

事情要注意:

  • item.Makeselect子句中的使用,而不是如果你的代码中有s.Make
  • 你有item.Model之间的空白在你where条款
+1

他没有Car []数组,名为CarList? –

+0

@Davide Piras,哦,是的。你是对的。我没有仔细阅读。感谢您发现这一点。立即更新我的答案。 –

0

做到这一点的最好办法:

ContexteDAO.ContexteDonnees实例化一个新的上下文。

public static Destination[] Rechercher(string aCodeDestination, string aDénomination, string aVille, string aPays, Single aLatitude, Single aLongitude, string aContinent, 
              string aZoneGeo, string aRelief,string aObservation) 
    { 
     IEnumerable<Destination> DestinationRecherche; 

     DestinationRecherche = ContexteDAO.ContexteDonnees.Destinations; 

     if(!string.IsNullOrEmpty(aCodeDestination)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a=>a.CodeDestination.Contains(aCodeDestination)); 
     } 
     if (!string.IsNullOrEmpty(aDénomination)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.Dénomination.Contains(aDénomination)); 
     } 
     if (!string.IsNullOrEmpty(aVille)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.Ville.Contains(aVille)); 
     } 
     if (!string.IsNullOrEmpty(aPays)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.Pays.Contains(aPays)); 
     } 
     if (aLatitude != 0) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.Latitude.Equals(aLatitude)); 
     } 
     if (aLongitude != 0) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.Longitude.Equals(aLongitude)); 
     } 
     if (!string.IsNullOrEmpty(aContinent)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.Continent.Contains(aContinent)); 
     } 
     if(!string.IsNullOrEmpty(aZoneGeo)) 
     {    DestinationRecherche = DestinationRecherche.Where(a => a.ZoneGeographique.Contains(aZoneGeo)); 
     }   
     if(!string.IsNullOrEmpty(aRelief)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a =>a.Relief.Contains(aRelief)); 
     } 
     if (!string.IsNullOrEmpty(aObservation)) 
     { 
      DestinationRecherche = DestinationRecherche.Where(a => a.ObservationsDestination.Contains(aObservation)); 
     } 
     return DestinationRecherche.ToArray(); 
    }