Roll filling dictionary in LINQ of For expression

I have a data object

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

with many of them on the 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 what I can do for or for each cycle to do this

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

But I want to either use the LINQ operator (preferred) or an expression for the loop . This is easy when only one element is returned, but is not sure of the syntax for two dictionary elements.

+3
source share
1 answer

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

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

I think the Delphi equivalent would be the following:

var dict := ol.ToDictionary(o -> o.s, o -> o);
+3
source

Source: https://habr.com/ru/post/1770817/


All Articles