문제

I have an ArrayList that looks like this

This is how clientArray was formed:

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);
    }
}

This is how clientArray looks like:

{
  "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...

I need to put all DISTINCT Codes into a list. What I have so far is returning all Codes (not what I want). How do I do this?

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

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

listOfCodes.Distinct().ToList();
도움이 되었습니까?

해결책

Something like this ought to do you:

ArrayList = GetMyArrayList() ;

...

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

Another approach would be to use HashSet<T> or SortedSet<T>, something like:

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 ) ;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top