Wednesday, 8 April 2015

c# linq sequence contains no elements

c# linq sequence contains no elements
Where condition on List using linq
Solution:
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; }
}
}
view raw gistfile1.cs hosted with ❤ by GitHub