Question

I have a data object

  Data = class
  public
    s: string;
    i: Integer;
  end;

with many of them in a list (or some collection):

  var ol : List<Data> := new List<Data>;
  ol.Add(new Data(s := 'One', i := 1));
  ol.Add(new Data(s := 'Two', i := 2));
  ol.Add(new Data(s := 'Three', i := 3));
  ol.Add(new Data(s := 'Four', i := 4));
  ol.Add(new Data(s := 'Five', i := 5));

And I want to put it in a dictionary:

  var l: Dictionary<string, data> := new Dictionary<String,Data>;

I know I can do a for or for each loop to do this

  for each d in ol do
  begin
    l.Add(d.s, d);
  end;

But I want to either use a LINQ statement (preferred) or a For Loop expression. It is easy when only returning one element, but not sure on the syntax for the two elements for a Dictionary.

Was it helpful?

Solution

EDIT: I jumped right into this but I'm not familiar with Delphi. In C# it would be as simple as this ToDictionary call:

var dict = ol.ToDictionary(o => o.s, o => o);

I think the Delphi equivalent would be:

var dict := ol.ToDictionary(o -> o.s, o -> o);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top