2012-08-22 67 views
0

我試圖獲取我的類對象的不同列表時出現問題。具有不同列表的C#Linq類

對於這個特定的查詢,我只對抓取DLType感興趣,有3種類型的「DLType」出現在我的列表中多次。我只想從數據中獲取這三種類型,並將其用於組合框的數據源。

這裏是我的班級: -

public class DistributionList 
{ 
    public int DistributionID { get; set; } 
    public string DistributionName { get; set; } 
    public string DLType { get; set; } 
} 

這裏是我搶的數據: -

public List<DistributionList> GetDistributionLists() 
{ 
    DataTable dt = new DataTable(); 

    OleDbCommand cmd = new OleDbCommand("Select * FROM [DistributionLists]", 
               Connection); 
    Adapter.SelectCommand = cmd; 

    Connection.Open(); 
    Adapter.SelectCommand.ExecuteNonQuery(); 
    Adapter.Fill(dt); 
    Connection.Close(); 

    var DistributionLists = (from d in dt.AsEnumerable() 
      select new DistributionList 
      { 
       DistributionID = d.Field<int>("DistributionID"), 
       DistributionName = d.Field<string>("DistributionName"), 
       DLType = d.Field<string>("DLType") 
      }).ToList(); 

    return DistributionLists; 

} 

這裏我提取數據到我的表格: -

var distributionData = dc.GetDistributionLists(); 

現在我需要從distributionData對象中獲得一個清晰的列表: -

var query = (from d in distributionData 
         select new DistributionList 
         { 
          DLType = d.DLType 

         }).Distinct().ToList(); 

但是這不起作用,有沒有辦法做到這一點?

回答

1

Linq的問題是它會爲每個值生成一個新的DistributionList - 並且因爲它們都是不同的實例,所以它們全部返回它們。嘗試重新安排你處理查詢,像這樣的方式:

var query = (from d in distributionData select d.DLType) 
        .Distinct() 
        .Select(t => new DistributionList() { DLType = t }) 
        .ToList(); 
+0

這是工作!謝謝!我一直堅持這個很長一段時間!我是LINQ的新手! – Derek

1

您需要在您的DistributionList類實現Equals。詳情請參閱this answer

1

不要選擇new DistributionList,選擇DLType

distributionData.Select(d => d.DLType).Distinct().ToList(); 
1

你只需要組列表通過一些獨特的功能鍵,選擇從每個組的第一個元素,這樣

(from d in distributionData 
         select new DistributionList 
         { 
          DLType = d.DLType 

         }).GroupBy(a=>a.DLType).Select(a=>a.First()).ToList() 
0

你可以以後有事使用lambda的Comparer的直觀方法:

public class LambdaComparer<T> : IEqualityComparer<T> 
{ 
    private readonly Func<T, T, bool> _lambdaComparer; 
    private readonly Func<T, int> _lambdaHash; 

    public LambdaComparer(Func<T, T, bool> lambdaComparer) : 
     this(lambdaComparer, o => 0) 
    { 
    } 

    public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash) 
    { 
     if (lambdaComparer == null) 
      throw new ArgumentNullException("lambdaComparer"); 
     if (lambdaHash == null) 
      throw new ArgumentNullException("lambdaHash"); 

     _lambdaComparer = lambdaComparer; 
     _lambdaHash = lambdaHash; 
    } 

    public bool Equals(T x, T y) 
    { 
     return _lambdaComparer(x, y); 
    } 

    public int GetHashCode(T obj) 
    { 
     return _lambdaHash(obj); 
    } 
} 

,然後使用它像如下:

var query = (from d in distributionData 
      select d) 
      .Distinct<DistributionList> 
      (new LambdaComparer<DistributionList>((x, y) 
           => x.DLType == y.DLType)); 

問候

相關問題