2015-05-20 29 views
0

我希望從wcf服務構建一個字典(該服務託管在服務器上)。如何構建一個字典查詢與Id作爲鍵和數據類作爲值在C#中的字典?

在我的應用程序中,每隔5分鐘,遠端用戶就會詢問服務以獲取該詞典。這個詞典將幫助我查看在密鑰的幫助下是否在用戶屏幕上顯示了一條消息。

我想要得到這樣的結果:

密鑰(ALERT_ID),值1(ALERT_TITLE,值2(alert_text)...

與元組dictionnary似乎是一個很好的解決方案,但我需要幫助的實現。

public Dictionnary<int, Tuple<Alert>> GetAlertDataItems() 
{ 
    Dictionnary<int, Tuple<Alert>> AlertData = new Dictionnary<int, Tuple<Alert>>(); 
    var q = 
    from p in db.AlertMap.Include(a=>a.AlertLog).Include(a=>a.AlertMode).Includ(a=>a.AlertPriority) 
    from t in db.RecipientMap 
    where ((p.AlertLog.AlertActive==true)&&(p.AlertID==t.AlertID)&&(DateTime.Now < p.AlertLog.AlertEndDate) 
    select p; 

    foreach (AlertMap singleAlert in q) 
    {...//I'm lost here 
    } 

    return AlertData; 
} 

Alert類

[DataContract] 
    public class Alert 
    { 
     [DataMember] 
     public int AlertId {get;set;} 
     [DataMember] 
     public string AlertModeCde{get;set;} 
     [DataMember] 
     public string AlertPriorityCde {get;set;} 
     [DataMember] 
     public string AlertTitle{get;set;} 
     [DataMember] 
     public string AlertText{get;set;} 
     [DataMember] 
     public DateTime AlertStartDate {get;set;} 
     [DataMember] 
     public DateTime AlertEndDate {get;set;} 
     [DataMember] 
     public byte AlertActive {get;set;} 
    } 

感謝任何幫助!

回答

1

的Linq有ToDictionary法內置:

在這種情況下
var AlertData = q.ToDictionary(a => a.AlertId, a => a); 

您的返回類型應該是Dictionnary<int, Alert>

或者僅僅提取警報標題和文本到一個元組:

var AlertData = q.ToDictionary(a => a.AlertId, 
           a => Tuple.Create(a.AlertTitle, a.AlertText)); 

在這種情況下,您的退貨類型應爲Dictionnary<int, Tuple<string, string>>

+0

謝謝!但我得到這個錯誤,你的第一個例子:不能隱式轉換類型'system.Collections.Generic.Dictionnary 在'system.Collections.Generic.Dictionnary '也許我會錯過一些東西關於轉換。 – mrplume

+0

@mrplume函數的返回類型必須與你的ToDictionary調用的'value'類型(第二個參數)相匹配。我不知道你想返回什麼 - 如果它是'AlertMap'則返回該類型。 –

0

你必須反覆結果和項目添加到字典逐個:

for(int i=0; i< q.Count(); i++) 
{ 
    AlertData.Add(i,new Tuple<Alert>(q[i])) 
} 

return AlertData; 
0

好,我已經找到了解決辦法:

public Dictionnary<int,Alert>GetAlertDataItems() 
{ 
    Dictionnary<int,Alert> AlertDict = new Dictionnary<int,Alert>(); 
    List<Alert> AlertData = new List<Alert>(); 

    var q = 
    from p in db.AlertMap.Include(a=>a.AlertLog).Include(a=>a.AlertMode).Includ(a=>a.AlertPriority) 
    from t in db.RecipientMap 
    where ((p.AlertLog.AlertActive==true)&&(p.AlertID==t.AlertID)&&(DateTime.Now < p.AlertLog.AlertEndDate) 
    select p; 

    foreach(AlertMap singleAlert in q) 
     { 
      Alert a = new Alert(); 
      a.AlertId = singleAlert.AlertID; 
      a.AlertTitle = singleAlert.AlertLog.AlertTitle; 
      .... 
      AlertData.Add(a); 
     } 

    foreach(Alert alert in AlertData) 
     { 
      if(!AlertDict.Keys.Contains(alert.AlertId)) 
      AlertDict.Add(alert.AlertId,alert); 
     } 
    return AlertDict; 
} 

這不是一個完美的解決方案,因爲我有我的alertid場兩次(一個作爲關鍵字,另一個作爲值),但是爲了測試,沒關係。

感謝您的幫助!

相關問題