2013-09-05 60 views
0

我有TransportType的列表,從 過濾應用程序應該比較此列表中的用戶選擇,那麼他只選擇了什麼回報應該是在定義列表與過濾條件C#查詢

private static readonly string[] ValidTransportType = new string[] 
    { 
     "Cars", 
     "Airplans", 
     "Audi", 
     "BMW", 
     "Airbus A333", 
     "Boing 747", 
    }; 

    public static IEnumerable<string> GetSelectedTypes(IEnumerable<string> userSelection) 
    { 
     var list = (from transport in ValidTransportType 
        where userSelection.Contains(transport) 
        select transport).ToList(); 

     return list; 
    } 

例如:如果用戶選擇「汽車」,「保時捷」,那麼結果將只是「汽車」,因爲保時捷未定義。

我的問題是,我如何修改Linq查詢來執行以下操作: 如果用戶選擇「Cars」,「Audi」,「BMW」,則查詢返回Cars,因爲汽車包括BMW和AUDI,如果用戶選擇如果用戶選擇了「BMW」,「AUDI」,「飛機」,「Boing 747」,那麼「奧迪」和「寶馬」將會返回「奧迪」和「寶馬」,但不會返回「汽車」應用程序應返回列表「寶馬」,「奧迪」,「飛機」,但不包括「波音747」飛機包括「波音747」

任何想法?

編輯:

請注意,類型和類型來比較的未知運行之前,無論是從exteranl文件來了,例如:在我的例子,我把車,但它可以是動物,技術,人......等等,這就是爲什麼我無法預測類型並預先創建類。

+1

在您當前形式你沒有汽車之間的關係 - >奧迪,寶馬。考慮一下寶馬,奧迪或寶馬和奧迪等字典結構的基類「汽車」,它的價值就像汽車一樣。 – Habib

+0

@Habib感謝您的回覆,問題是輸入來自外部csv文件,並且要比較的列表也來自外部文件。它可以是汽車,動物什麼的,但總是有一個抽象類型,這是文件(汽車,飛機,動物等)中的每一行的第一個單詞 – Maro

+0

然後我會建議有'Dictionary 「,每個項目作爲鍵和值作爲它們的類型。稍後,您可以通過類型訪問它們,但必須在對象中有關係才能獲取相關數據。 – Habib

回答

1

沒有linq查詢,它實際上更容易,但使用簡單的舊的foreach循環。

首先,讓我們創建一個字典組BMWAudiCars組等:

var d = new Dictionary<string, List<string>>(); 
string[] items = {"Cars,BMW", "Cars,Audi", "Animals,Dog"}; 
foreach (var item in items) 
{ 
    // TODO: use better variable names 
    // you probably use a csv parser for this 
    var s = item.Split(','); 

    // fill the dictionary. 
    if (!d.ContainsKey(s[0])) 
     d[s[0]] = new List<string>(); 
    d[s[0]].Add(s[1]); 
} 

然後,GetSelectedTypes實施看起來是這樣的:

public static IEnumerable<string> GetSelectedTypes(Dictionary<string, List<string>> validTypes, IEnumerable<string> userSelection) 
{ 
    foreach (var kvp in validTypes) 
     // if the key is in userSelection, only return the key, but no items 
     if (userSelection.Contains(kvp.Key)) 
      yield return kvp.Key; 
     // if not, only return valid items 
     else 
      foreach (var item in kvp.Value) 
       if (userSelection.Contains(item)) 
        yield return item; 
} 

簡單的測試:

string[] userSelection = {"Cars", "Audi", "Dog"}; 
// will be [Cars, Dog], because Cars include Audi 
GetSelectedTypes(d, userSelection); 

string[] userSelection2 = {"BMW", "Audi", "Dog", "Animals"}; 
// will be [BMW, Audi, Animals] because Animals include Dog 
GetSelectedTypes(d, userSelection2);