2011-09-07 79 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(); 
    }