Home > Net >  Splitting a Dictionary with a list in half in C#
Splitting a Dictionary with a list in half in C#

Time:09-21

I have a C# dictionary defined as following..

Dictionary<string, List<FirstReportsData>> dict1 =
  new Dictionary<string, List<FirstReportsData>>();

The List within my dictionary is defined as follows:

public class FirstReportsData
{
  public FirstReportsData() { }

  public int    Id { get; set; }
  public int    FirstReportsItemId { get; set; }
  public string Policy { get; set; }
  public string CarrierCode { get; set; }
  public string StateCode { get; set; }
  public string RecordTypeCode { get; set; }
  public string RecordData { get; set; }

}

The string (key) in the dictionary maybe a value for example like say "07", "00", or "09" . How do I take only the first half of the list with the key "00" and put it into a new dictionary. I then would also like to take the second half of the list from key "00" and put it into a second dictionary. Any possible direction on the approach or syntax needed would be greatly appreciated.

CodePudding user response:

Dictionary<KeyValuePair<TKey, TValue>> implements IEnumerable<T>, so you can do this with relatively simple LINQ.

var firstHalf = dict1.Where(d => d.Key == "00").Take(dict1.Count / 2);
var secondHalf = dict1.Where(d => d.Key == "00).Except(firstHalf);

CodePudding user response:

Something like this:

List<FirstReportsData> list1 = new List<FirstReportsData>();
List<FirstReportsData> list2 = new List<FirstReportsData>();

foreach(KeyValuePair k in dict1){
    list1.Add(k.Key);
    list2.Add(k.Value);
}

This will loop through your list and add the keys to one list and the values to another list.

  • Related