c# linq sequence contains no elements
Where condition on List using linq
Solution:
Where condition on List using linq
Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Web.UI; | |
using System.Web.UI.WebControls; | |
namespace Test.linq | |
{ | |
public partial class WebForm1 : System.Web.UI.Page | |
{ | |
public List<Cars> myCars = new List<Cars>{ | |
new Cars(){Name="Honda",Color="Red"}, | |
new Cars(){Name="Nisan",Color="Red"}, | |
new Cars(){Name="Toyota",Color="Silver"}, | |
new Cars(){Name="BMW",Color="Black"} | |
}; | |
protected void Page_Load(object sender, EventArgs e) | |
{ | |
//Find my car color from myCars list | |
int iIndex = 0; | |
//First i am checking whether my Car is exist or not in myCars list. | |
var idump = myCars.FirstOrDefault(p => p.Name == "Honda"); | |
//If exist it will not be null or it will be null | |
if (idump != null) | |
{ | |
iIndex = myCars.Select((Value, Index) => new { Value, Index }).Single(p => p.Value.Name == "Honda").Index; | |
} | |
else | |
{ | |
iIndex = -1; | |
} | |
if (iIndex != -1) | |
{ | |
string strCarColor = myCars[iIndex].Color.ToString(); | |
Response.Write("Your car color" + strCarColor); | |
} | |
else | |
{ | |
Response.Write("Your car is no available."); | |
} | |
} | |
} | |
public class Cars | |
{ | |
public string Name { get; set; } | |
public string Color { get; set; } | |
} | |
} |