all things Sitecore related

LINQ: Creating a if statement in Linq query

By on July 30, 2009 in ASP.Net, linq with 0 Comments

A lot of times I need to check a statement within my LINQ-query and I wish there was a possibility of a IF statement within LINQ.

The following code is the solution to my IF problem. I use a temporary variable (let isOlderThen30) to check if a statement is true. Then in my WHERE statement I use the temporary variable in a INFLINE IF.

For this example I use my Blogger class with some data



public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}

List<Blogger> personList = new List<Blogger>{
 new Blogger { FirstName = "Pieter", LastName = "Brinkman", Age = 27, Blog = "http://blog.newguid.net" },
 new Blogger { FirstName = "Mark", LastName = "van Aalst", Age = 26, Blog = "http://www.markvanaalst.com" },
 new Blogger { FirstName = "Bas", LastName = "Hammendorp", Age = 32, Blog = "http://www.hammendorp.net" }
};


It’s kind of hard to think of a easy good example, but here it is. In this example I want to set the Age property to “Older then 30″ when the Blogger is older then 30 (how useful!).


//If a blogger is older then set Age text to "Older then 30"

var rawList = from item in personList
  let <strong>isOlderThen30</strong> = item.Age > 30
  select new
  {
   Name = item.FirstName,
   Age = (isOlderThen30 ? "Older then 30" : item.Age.ToString()),
  };

//GENERATE OUTPUT

foreach (var item in rawList)
{
 Response.Write(item.Name + " (" + item.Age + ")<br/>");
}

//OUTPUT
//Pieter (27)
//Mark (26)
//Bas (Older then 30)


Hope that the example is clear. If you have any questions let me know.

// UPDATE (3 aug 2009) //

I thought about the codeexample and offcourse you can do it shorter (but less readable with complex queries).


var rawList = from item in personList
  select new
  {
   Name = item.FirstName,
   Age = (item.Age > 30 ? "Older then 30" : item.Age.ToString()),
  };


About the Author

About the Author: Pieter is Technical Marketing Manager for Sitecore Netherlands and owner of Gaatverweg.nl. He has more than ten years experience with software developing in multiple programming languages and with different Content Management Systems. Before joining Sitecore Pieter was a lead developer for multiple Sitecore and .Net projects, he joined Sitecore in 2011 as an Solution Architect in The Netherlands, after two years as an Solution Architect he joined the Technical Marketing department. In the role as Techinical Marketing Manager he is responsible for the Global MVP program and the Sitecore technical branding strategy. You can follow Pieter on twitter: @pieterbrink123 or Google+ .

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Post a Comment

Your email address will not be published. Required fields are marked *

Top