带有LINQ查询的字典 [英] Dictionary with LINQ Query

查看:68
本文介绍了带有LINQ查询的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用LINQ.

我必须填充一个Dictionary< string,int>像

这样的LINQ查询

 

< int 来自 plateList 加入 stf StiffenerList plt.id 等于 stf.plateId 选择 {plt.name,plt.id}).ToDictionary< 字符串 int 我必须生成pltList.

任何人都可以完成上述查询以填充pltList.我尝试了很多,但没有得到实际的结果.

 

预先感谢

卫星

解决方案

嗨!

不要试图强制运行时将string和int用作类型参数,而应让它尝试从您在方法调用中编写的lambda推断出它. :)(棘手的一个,当您编写ToDictionary< string,int>时,仅显示2个cos重载,并且您需要另一个重载.)

这是一些代码:

 

课程
{
  静态void Main(string [] args)
  {
    List< Plate> plateList = new List< Plate>
    {
      新版{ID = 0,名称=阿拉木图"},
      新版{ID = 1,名称="bé ka"},
      新版{ID = 2,名称="kö rte"}
    };

    var pltList =(来自plateList中的plt
           选择新的{plt.Name,plt.Id})
           .ToDictionary(e => e.Name,e => e.Id);

    foreach(pltList中的var项)
      Console.WriteLine(string.Format(键:{0},值:{1}",item.Key,item.Value));

    Console.ReadLine();
  }
}

类板
{
  public int ID {get;放; }
  公共字符串名称{get;放; }
  public int SomethingElse {get;放; }
}

 如您所见,ToDictionary的此重载接受两个lambda:一个用于键,一个用于值.

希望我能帮上忙!

David


Hi ,

I started using LINQ.

I have to populate a Dictionary<string,int> with a LINQ query like

Dictionary

 

<string,int> pltList = (from plt in plateList join stf in StiffenerList on plt.id equals stf.plateId select new { plt.name, plt.id }).ToDictionary<string,int> _____

i have to generate pltList .

Can anyone complete the above query to populate pltList. I tried so many but i didn't get actual thing.

 

Thanks in Advance

Sateesh

解决方案

Hi!

Don't try to force the runtime to use string and int as type params, let it try to infer it from the lambdas you write in the method call. :) (Tricky one, cos only 2 overloads show up when you write ToDictionary<string, int>, and you need another one.)

Here is some code:

 

class Program
{
  static void Main(string[] args)
  {
    List<Plate> plateList = new List<Plate>
    {
      new Plate { Id = 0, Name = "alma"},
      new Plate { Id = 1, Name = "béka"},
      new Plate { Id = 2, Name = "körte"}
    };

    var pltList = (from plt in plateList
           select new { plt.Name, plt.Id })
           .ToDictionary(e => e.Name, e => e.Id);

    foreach (var item in pltList) 
      Console.WriteLine(string.Format("Key: {0}, value: {1}", item.Key, item.Value));

    Console.ReadLine();
  }
}

class Plate
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int SomethingElse { get; set; }
}

 As you can see, this overload of ToDictionary accepts two lambdas: one for the key, one for the value.

Hope I could help!

David


这篇关于带有LINQ查询的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆