开发者

Roll populating a Dictionary into a LINQ of For expression

开发者 https://www.devze.com 2023-01-21 15:04 出处:网络
I have a data object Data = class public s: string; i: Integer; end; with many of them in a list (or some collection):

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 (prefer开发者_如何学Gored) 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号