C# 序列包含多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1256757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequence contains more than one element
提问by
I'm having some issues with grabbing a list of type "RhsTruck" through Linq and getting them to display.
我在通过 Linq 获取“RhsTruck”类型的列表并让它们显示时遇到了一些问题。
RhsTruck just has properites Make, Model, Serial etc... RhsCustomer has properties CustomerName, CustomerAddress, etc...
RhsTruck 只有属性 Make、Model、Serial 等... RhsCustomer 有属性 CustomerName、CustomerAddress 等...
I keep getting the error "Sequence contains more than one element". Any ideas? Am I approaching this the wrong way?
我不断收到错误“序列包含多个元素”。有任何想法吗?我是否以错误的方式接近这个?
public RhsCustomer GetCustomer(string customerNumber)
{
using (RhsEbsDataContext context = new RhsEbsDataContext() )
{
RhsCustomer rc = (from x in context.custmasts
where x.kcustnum == customerNumber
select new RhsCustomer()
{
CustomerName = x.custname,
CustomerAddress = x.custadd + ", " + x.custcity
CustomerPhone = x.custphone,
CustomerFax = x.custfax
}).SingleOrDefault();
return rc;
}
}
public List<RhsTruck> GetEquipmentOwned(RhsCustomer cust)
{
using (RhsEbsDataContext context = new RhsEbsDataContext())
{
var trucks = (from m in context.mkpops
join c in context.custmasts
on m.kcustnum equals c.kcustnum
where m.kcustnum == cust.CustomerNumber
select new RhsTruck
{
Make = m.kmfg,
Model = m.kmodel,
Serial = m.kserialnum,
EquipID = m.kserialno1,
IsRental = false
}).ToList();
return trucks;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string testCustNum = Page.Request.QueryString["custnum"].ToString();
RhsCustomerRepository rcrep = new RhsCustomerRepository();
RhsCustomer rc = rcrep.GetCustomer(testCustNum);
List<RhsTruck> trucks = rcrep.GetEquipmentOwned(rc);
// I want to display the List into a Gridview w/auto-generated columns
GridViewTrucks.DataSource = trucks;
GridViewTrucks.DataBind();
}
回答by JaredPar
The problem is that you are using SingleOrDefault
. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault
which will succeed no matter how many elements are in the collection.
问题是您正在使用SingleOrDefault
. 只有当集合恰好包含 0 或 1 个元素时,此方法才会成功。我相信您正在寻找FirstOrDefault
无论集合中有多少元素都能成功的方法。
回答by Mehmet Aras
SingleOrDefault
method throws an Exception
if there is more than one element in the sequence.
SingleOrDefault
Exception
如果序列中有多个元素,方法将抛出一个。
Apparently, your query in GetCustomer
is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.
显然,您的查询GetCustomer
找到了多个匹配项。因此,您要么需要优化您的查询,要么最有可能检查您的数据,以了解为什么您会为给定的客户编号获得多个结果。
回答by Martin Sax
As @Mehmet is pointing out, if your result is returning more then 1 elerment then you need to look into you data as i suspect that its not by design that you have customers sharing a customernumber.
正如@Mehmet 所指出的那样,如果您的结果返回超过 1 个元素,那么您需要查看您的数据,因为我怀疑您的客户共享客户编号并非有意为之。
But to the point i wanted to give you a quick overview.
但是,我想给你一个快速的概述。
//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();
//success on 0-n, returns first element in the list or default() if 0
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();
//success on 0-n, returns first element in the list or default() if 0
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();
for more Linq expressions have a look at System.Linq.Expressions
有关更多 Linq 表达式,请查看System.Linq.Expressions
回答by Chris Moschini
FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.
仅供参考,如果 EF 迁移尝试在未配置 Db 的情况下运行,例如在测试项目中,您也会收到此错误。
Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.
在我发现它在查询中出错之前追了几个小时,但是,不是因为查询,而是因为迁移开始尝试创建数据库。
回答by Muhammad Armaghan
Use FirstOrDefault insted of SingleOrDefault..
SingleOrDefault returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing
SingleOrDefault 返回一个 SINGLE 元素,如果没有找到元素,则返回 null。如果在您的 Enumerable 中找到 2 个元素,则它会抛出您看到的异常
FirstOrDefault returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored
FirstOrDefault 返回它找到的第一个元素,如果没有找到元素,则返回 null。因此,如果有 2 个元素与您的谓词匹配,则忽略第二个元素
public int GetPackage(int id,int emp)
{
int getpackages=Convert.ToInt32(EmployerSubscriptionPackage.GetAllData().Where(x
=> x.SubscriptionPackageID ==`enter code here` id && x.EmployerID==emp ).FirstOrDefault().ID);
return getpackages;
}
1. var EmployerId = Convert.ToInt32(Session["EmployerId"]);
var getpackage = GetPackage(employerSubscription.ID, EmployerId);