Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用LINQtoSQL投影到具有自定义类型的字典?_C#_.net_Sql_Linq - Fatal编程技术网

C# 如何使用LINQtoSQL投影到具有自定义类型的字典?

C# 如何使用LINQtoSQL投影到具有自定义类型的字典?,c#,.net,sql,linq,C#,.net,Sql,Linq,我试图使用Linq将DB查询中的每一行投影到一个字典中,该字典的值为自定义类型。我不确定执行此操作的LINQ语法 这是我当前的尝试(它没有编译,但应该演示我正在尝试做什么)。我在“选择新…”部分遇到问题 public class MyClass { public Dictionary<int, CustomType> dict; } public class MyType{ string Name; decimal Value; } v

我试图使用Linq将DB查询中的每一行投影到一个字典中,该字典的值为自定义类型。我不确定执行此操作的LINQ语法

这是我当前的尝试(它没有编译,但应该演示我正在尝试做什么)。我在“选择新…”部分遇到问题

public class MyClass
{     
   public Dictionary<int, CustomType> dict;
}

public class MyType{        
   string Name;
   decimal Value;
}

var result = (from t in table
              select new {
                 t.Id,
                 new MyType(t.Name,t.Value)
              }).AsEnumerable().ToDictionary();
公共类MyClass
{     
公共词典;
}
公共类MyType{
字符串名;
十进制值;
}
var结果=(来自表中的t
选择新的{
t、 身份证,
新MyType(t.Name,t.Value)
}).AsEnumerable().ToDictionary();
答复:

谢谢你,杰森。我只是使用属性和自动初始化器,而不是构造函数。工作代码类似于此(欢迎对此进行任何改进):

公共类MyType{
公共字符串名称{get;set;}
公共十进制值{get;set;}
}
词典词典;
dict=(从表中的t开始)
选择新的{
id=av.Account.id,
mt=newmytype{Name=t.Name,Value=t.Value}
}).ToDictionary(item=>item.id,item=>item.mt);

MyType
没有接受两个参数的构造函数

将以下内容添加到MyType的定义中:

public MyType(string name, decimal value) {
    Name = name; 
    Value = value;
}
此外,您没有提供由定义的匿名类型成员

new MyType(t.Name, t.Value)
一个名字;尝试将该行更改为:

MyType = new MyType(t.Name, t.Value)
编译器会对您大喊大叫,说它无法识别此匿名成员的名称

最后,没有没有没有参数的
ToDictionary
重载。假设您将上述匿名成员命名为
MyType
,则将调用更改为
ToDictionary

....ToDictionary(item => item.Id, item => item.MyType);
....ToDictionary(item => item.Id, item => item.MyType);