C#: Remove line from textfile

With the following code you can remove a line from a textfile (web.config). If the string is within a line the line will be removed.

string configFile = @"C:devweb.config";
List lineList = File.ReadAllLines(configFile).ToList();
lineList = lineList.Where(x => x.IndexOf("<!--") <= 0).ToList();
File.WriteAllLines(configFile, lineList.ToArray());

LINQ: Creating a if statement in Linq query

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 personList = new List{
 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 &gt; 30
  select new
   Name = item.FirstName,
   Age = (isOlderThen30 ? "Older then 30" : item.Age.ToString()),


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

//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 &gt; 30 ? "Older then 30" : item.Age.ToString()),

Linq to Xml: Generate Google Sitemap with sitemap-protocol

In this example I will generate a XML site-map that complies with the sitemap-protocol XML schema.

//create datasource

List blogPosts = new List{

//Create namespace for sitemap-protocol

XNamespace xmlNS = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xmlDoc =
 new XDocument(
  new XDeclaration("1.0", "UTF-8", null),
  new XElement(xmlNS + "urlset",
   from blogPostUrl in blogPosts
    new XElement(xmlNS + "url",
    new XElement(xmlNS + "loc", blogPostUrl))

//Show output


This example will give the following output:

&lt;urlset xmlns=&quot;<a href="http://www.sitemaps.org/schemas/sitemap/0.9">http://www.sitemaps.org/schemas/sitemap/0.9</a>"&gt;

To keep the example as simple as possible I only use the LOC element of the URL node. In the real world you can implement the lastmod, changefreq and priority node.

More information about the sitemap-protocol.

Linq Casting: ToDictionary()

In this post I will give an example how to cast a GenericList to Dictionary.

This example will use the following Blogger class.

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

The example will cast a List<Blogger> to a dictionary with key FirstName, Lastname and value the Age of the blogger.


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

// with key FirstName + LastName and value Age

Dictionary AgeDictionary =
 personList.ToDictionary(x =&gt; x.FirstName + " " + x.LastName,
       x =&gt; x.Age,


foreach (KeyValuePair item in AgeDictionary)
 Response.Write("key: " + item.Key + " - value: " + item.Value + "<br />");

//key: Pieter Brinkman - value: 27
//key: Mark van Aalst - value: 26
//key: Bas Hammendorp - value: 32

 Hope it helps.

WCF webservice error with DBML objects

When deploying a WCF webservice for a Silverligh application I got the following error:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: <a href="http://tempuri.org/:IWebService">http://tempuri.org/:IWebService</a> ----&gt; System.Runtime.Serialization.InvalidDataContractException: Type 'Project.service.HU_BACH.ScPlacemark' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.

As you can see from the error you need to add the [Serializable] attribute to all objects that are used within the webservice. After I did this I got the same error for my Linq to Sql objects generated within my DBML. You can make your Linq to Sql objects serializable by changing the dbml setting Serialization Mode to Unidirectional.

Hope it helps.

Linq to Sql: Retrieve properties from related data (LoadWith)

You have to specify which related-data you want to retrieve from a object so you can access them outside the Linq data-context. You can achieve this by using the LoadWith method of the DataLoadOptions Class. The LoadWith method accepts an lambda expression that specifies which object you want to retrieve.

In the following example I have a employee table that has a relation with the company table. In my code I want to show the employee with the company name (outside the DataContext).

Employee employee;

using (LinqDataContext db = new (LinqDataContext())
   DataLoadOptions dlo = new DataLoadOptions(); 
   dlo.LoadWith(e =&gt; e.Company);
   db.LoadOptions = dlo;

   employee = from item in db.Employees
                      select item).First();

string companyName = employee.Company.Name;

Because of the DataLoadOptions I can now use the company properties to print the company name outside the DataContext.


Convert XmlElement to XElement (Extension Method)

I was using some web-services that returned there values in an XmlElement. I needed to convert this XmlElement to something that I can use with LINQ. I didn't find good solutions on the internet. So I started building my own convert logic. After all kinds of solutions I ended up with creating an new XmlDocument, adding the XmlElement to the XmlDocument and then convert the innerXml of the XmlDocument to an XElement. Not really nice but it does the trick.

I've rewritten the code into a Extension Method for the XmlElement.


public static XElement ToXElement(this XmlElement xml)
   XmlDocument doc = new XmlDocument();

   doc.AppendChild(doc.ImportNode(xml, true));

   return XElement.Parse(doc.InnerXml);



You use the Extension Method like this:


XmlElement xmlElement = wsClient.DoWebServiceRequest();
XElement xml = xmlElement.ToXElement();


Please tell me if you have a better way of doing this!