views:

35

answers:

1

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.

+3  A: 

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);
Ahmad Mageed
I knew it was something really simple. Thanks!
Jim McKeeth
@Jim great! I had no idea Delphi added support for LINQ. I learnt something new :)
Ahmad Mageed
Yes, except it was ol.ToDictionary(o -> o.s, o -> o); since I wanted the object as the value. In the actual code the object is more complex than one value.
Jim McKeeth
@Ahmad: It is actually Delphi Prism, which is powered by Oxygene and is a .NET and Mono only version of Delphi that runs in Visual Studio.
Jim McKeeth
@Jim fixed. Thanks for the info!
Ahmad Mageed