LINQ Approach to filter SharePoint List and view only given column programmatically:
We can easily filter a SharePoint List using CAML Query but Microsoft is phasing out CAML query with new version of SharePoint . In this example I want to show how you can filter the SharePoint List using LINQ. This is very fast and good approach. Lets say I have SharePoint List called Customer and it has three column Name, State and City. In this example i will filter the item based on Name and State column and return the City value.
1. First you need to add following name space:
using System.Linq;
2. Code snippet to filter the list is below:
We can easily filter a SharePoint List using CAML Query but Microsoft is phasing out CAML query with new version of SharePoint . In this example I want to show how you can filter the SharePoint List using LINQ. This is very fast and good approach. Lets say I have SharePoint List called Customer and it has three column Name, State and City. In this example i will filter the item based on Name and State column and return the City value.
1. First you need to add following name space:
using System.Linq;
2. Code snippet to filter the list is below:
SPList myList = ReferenceWeb.Lists["Customer"];
IEnumerable TranslationItem = myList.Items.OfType();
var qry = from row in TranslationItem.Distinct()
where Convert.ToString(row["Name"]) == "Krish" &
Convert.
ToString (row["State"]) == "NJ"
select new
{
row.Title, // This will give you title if any.
CityName = Convert.ToString(row["City"]) // Here CityName is just a variable.
};
Lets say it returns one string value(city), how do we get it?
if (
qry .Count() > 0) // check if your it returns any item or not.
{
string strCity=qry.ElementAt(0).CityName ;
}
If it returns more than one value you can convert it to DataTable, List or Array.
Eg:
qry .ToList();
Tag: LINQ, ShrePoint, Filter SPList.
~ Happy Coding...
No comments:
Post a Comment