Please confirm whether they match, if they do not match you will get the same error as you.
This is my tested code, works fine on my side.
List<user> orderList = new List<user>() { new user() { Name="aaa",orderid=1} };
List<users> ordergroup = new List<users>() { new users() {name="bbb",Id=1} };
try
{
foreach (var obj in orderList)
{
obj.Name = ordergroup.First(x => x.Id == obj.orderid).name;
}
}
catch (Exception ex)
{
throw (ex);
}
class user
{
public int orderid { get; set; }
public string Name { get; set; }
}
class users
{
public int Id { get; set; }
public string name { get; set; }
}
Best regards,
Sam
IIS.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
If there is no match found then i get the above error "Sequence contains no matching element" and it throws an exception . How can i avoid this ?
The First() is going to throw an exception if the criteria is not met. It should be FirstOrDefault().
FirstOrDefault() returns the first object if one or more objects meet the criteria or a null valued object is returned that you'll have to check if no object is found that meets the criteria..
Member
283 Points
1004 Posts
How can i handle the Linq error "Sequence contains no matching element"
Jun 09, 2020 01:28 AM|robby32|LINK
Hi
i have the linq as follows:
orderList and ordergroup are 2 lists
foreach (var obj in orderList)
{
obj.Name = ordergroup.First(x => x.Id == obj.orderid).name;
}
If there is no match found then i get the above error "Sequence contains no matching element" and it throws an exception . How can i avoid this ?
Contributor
3370 Points
1409 Posts
Re: How can i handle the Linq error "Sequence contains no matching element"
Jun 09, 2020 03:30 AM|samwu|LINK
Hi robby32,
Please confirm whether they match, if they do not match you will get the same error as you.
This is my tested code, works fine on my side.
Best regards,
Sam
Contributor
4973 Points
4259 Posts
Re: How can i handle the Linq error "Sequence contains no matching element"
Jun 09, 2020 03:37 AM|DA924|LINK
ordergroup.First(x => x.Id == obj.orderid).name
If there is no match found then i get the above error "Sequence contains no matching element" and it throws an exception . How can i avoid this ?
The First() is going to throw an exception if the criteria is not met. It should be FirstOrDefault().
FirstOrDefault() returns the first object if one or more objects meet the criteria or a null valued object is returned that you'll have to check if no object is found that meets the criteria..
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault?view=netcore-3.1