从C#中的ArrayList获取不同的值

时间:2014-04-09 16:49:52

标签: c# linq arraylist distinct

我有ArrayList看起来像这样

这就是clientArray的形成方式:

ArrayList clientArray = new ArrayList();

foreach (Dictionary<string, object> media in mediaList)
{
    // get the Advertisers container object
    Dictionary<string, object> clientContainer = (Dictionary<string, object>)media["Advertisers"];

    //get the list of Advertisers (clients)
    var clientList = clientContainer["Advertiser"] as ArrayList;
    var clientListList = clientList.Cast<Dictionary<string, object>>().ToList();

    //add fields not olalready in the dictionary
    clientListList.ForEach(d => d.Add("MediaCode", media["Code"].ToString()));
    clientListList.ForEach(d => d.Add("MediaName", media["Name"].ToString()));
    clientListList.ForEach(d => d.Add("AgencyAlpha", mediaResponse["AgencyAlpha"].ToString()));
    clientListList.ForEach(d => d.Add("CreatedBy", System.Reflection.Assembly.GetExecutingAssembly().FullName.ToString()));
    clientListList.ForEach(d => d.Add("CreatedDt", DateTime.Now));

    foreach (Dictionary<string, object> client in clientListList)
    {
        clientArray.Add(client);
    }
}

这就是clientArray的样子:

{
  "client": [
    {
      "Code": "ABC",
      "Name": "ABC Inc",
      "BusinessKey": "ABC123",
      "MediaCode": "I",
      "MediaName": "Interactive",
      "AgencyAlpha": "UB",
      "CreatedBy": "DataApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
      "CreatedDt": "2014-04-08T12:47:54.5855957-04:00"
    },
    {
      "Code": "DEF",
      "Name": "DEF Inc",
      "BusinessKey": "DEF456",
      "MediaCode": "I",
      "MediaName": "Interactive",
      "AgencyAlpha": "UB",
      "CreatedBy": "DataApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
      "CreatedDt": "2014-04-08T12:47:54.5855957-04:00"
    },
etc...

我需要将所有DISTINCT Code放入列表中。到目前为止我所做的是返回所有 Code(不是我想要的)。我该怎么做?

List<string> listOfCodes = new List<string>();

foreach (Dictionary<string, object> obj in clientArray as IEnumerable)
{
    listOfCodes.Insert(0, obj["Code"].ToString());
}

listOfCodes.Distinct().ToList();

1 个答案:

答案 0 :(得分:2)

这样的事应该对你有用:

ArrayList = GetMyArrayList() ;

...

List<string> ListOfCodes = clientArray
.Cast<Dictionary<string,object>>()
.Select( x => x["Code"] as string)
.Distinct( StringComparer.OrdinalIgnoreCase )
.ToList()
;

另一种方法是使用HashSet<T>SortedSet<T>,例如:

IEnumerable<string> codeBag = clientArray
                              .Cast<Dictionary<string,object>>()
                              .Select( x => x["Code"] as string)
                              .Where( s => !string.IsNullOrEmpty(s) )
                              ;
HashSet<string>     codeSet = new HashSet<string>( codeBag , StringComparer.OrdinalIgnoreCase ) ;