gpt4 book ai didi

c# - Linq 方法有问题

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:20 24 4
gpt4 key购买 nike

我有以下方法:

public List<test_view> SelectTypeAnonimowe(string filtr)
{
testViewClassDataContext tv = new testViewClassDataContext();

List<test_view> q7 = tv.test_views
.Where(w => w.FirstName.StartsWith("H") && w.Type == filtr)
.Select(p => new {p.AutoName, p.LastName })
.ToList();

return q7;
}

我的错误: enter image description here

请告诉我哪里出了问题?

最佳答案

这是因为您将匿名类型强加到您的test_view 类型中。您应该创建 test_view 结果:

List<test_view> q7 = tv.test_views
.Where(w => w.FirstName.StartsWith("H") && w.Type == filtr)
.Select(p => new test_view(p.AutoName, p.LastName))
.ToList();

话虽这么说,您的test_view 应该有一个将两个变量作为输入的构造函数。像这样:

public string AutoName {get; private set;}
public string LastName {get; private set;}
public test_view(string autoName, string lastName){
AutoName = autoName;
LastName = lastName;
}

请注意,上面的选项不适用于 LINQ to entities 因为 LINQ to entities 需要无参数构造函数。或者,只要您的 test_view 具有以下两个属性:

public string AutoName {get; set;} //public property here
public string LastName {get; set;} //public property here
public test_view(){ //parameterless constructor here
}

您也可以像这样初始化属性(连同 test_view 创建):

List<test_view> q7 = tv.test_views
.Where(w => w.FirstName.StartsWith("H") && w.Type == filtr)
.Select(p => new test_view() {AutoName = p.AutoName, LastName = p.LastName})
.ToList();

关于c# - Linq 方法有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com