Select the index of a specific object via LINQ

This will search for the index of an object in a collection depending on a specific criteria.
When the object is not found in the collection, it will return an index with value -1.


string searchValue = "d";
List<string> items = new List<string>() { "a", "b", "c", "d", "e" };

int foundIndex = items.Select((x, i) => new { x, i })
.Where(x => x.x == searchValue)
.Select(x => x.i)
.DefaultIfEmpty(-1)
.First();

// specific code for LINQPad
foundIndex.Dump();

The result will be 3, because “d” has index 3 in the collection.

Advertisements

SelectMany in LINQ (C#)

This is an example of using SelectMany in Linq (Method notation):


string[] allItems = { "item1", "item2", "item3" };
string[] databaseItems = { "item2" };

var data = allItems
.SelectMany(item => databaseItems , (item, dbItem) => new { item, dbItem })
.Where(x => !x.item.Equals(x.dbItem, StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.item);

foreach (var v in data)
Console.WriteLine(v.ToString());

// LinqPad specific code:
data.Dump();

The result is item1 and item3.
This example takes all the items from allItems that don’t exist in databaseItems.

C# ExpandoObject

The ExpandoObject is actually pretty cool in C#. The dynamic keyword is actually pretty powerfull but might give you some Runtime Errors. 😉

var vs. dynamic keyword:
If you use the dynamic keyword, the type is decided at runtime. When using the var keyword, the compiler checks which type should be used when building/compiling.

I wrote a little example so that you could see the ExpandoObject and the dynamic keyword in action:


using System;
using System.Dynamic;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
dynamic _MyDog = new ExpandoObject();

_MyDog.BarfEvent = null;
_MyDog.BarfEvent += new EventHandler(OnBarf);

_MyDog.Name = "Lassie";
_MyDog.Age = "3";

_MyDog.Family = new ExpandoObject();
_MyDog.Family.Father = "Tramp";
_MyDog.Family.Mother = "Lady";

_MyDog.FavoriteFood = new string[2];
_MyDog.FavoriteFood[0] = "Cats";
_MyDog.FavoriteFood[1] = "Sausages";

_MyDog.Barf = new Action(() =>
{
Console.WriteLine("Bark Bark!");

// calling the event
EventHandler tmp = _MyDog.BarfEvent;
if (tmp != null)
tmp(_MyDog, new EventArgs());
});

// testing everything
Console.WriteLine(_MyDog.Name);
Console.WriteLine(_MyDog.Age);
Console.WriteLine(_MyDog.Family.Father);
Console.WriteLine(_MyDog.Family.Mother);
Console.WriteLine(_MyDog.FavoriteFood[0]);
Console.WriteLine(_MyDog.FavoriteFood[1]);
_MyDog.Barf();

Console.ReadLine();
}

public static void OnBarf(object sender, EventArgs e)
{
Console.WriteLine("I barked");
}
}
}

Enjoy 😉

Thread-safe event raising

Normally you would write this to make a temporary copy of your event in case something happend with SomeEvent:

EventHandler tmp = SomeEvent;

if (tmp != null) tmp(this, EventArgs.Empty);

Well you might consider this code below according to Jeffrey Richter his CLR via C# book.
The code above can cause some trouble because a compiler might optimize this code and remove the temporary copy of your event (depends on the implementation of the compiler).


EventHandler tmp = Interlocked.CompareExchange(ref SomeEvent, null, null);

if (tmp != null) tmp(this, e);

[ source ]

C# Triple XOR: swapping two variables without a temporary variable

Swapping two variable values without using a temporary variable can be accomplished by using a triple XOR.

This is a little hack or trick that was used in the past but which is a bit obsolete now. The compiler is normally smart enough to optimize your temporary variable code.

Note that this code can give you bad results (might give you different result when using i.e. floats)

using System;

namespace ConsoleApplication1
{
 class Program
 {
   static void Main(string[] args)
   {
     Console.WriteLine(string.Format("Result: {0}", Class1.WriteReverse("The quick brown fox jumps over the lazy dog.")));
     Console.ReadLine();
   }
 }

 public class Class1
 {
   public static string WriteReverse(string s)
   {
     if (string.IsNullOrEmpty(s)) return "Not valid";

     char[] c = s.ToCharArray();
     int j = s.Length - 1;

     for (int i = 0; i < j; i++, j--)
     {
       c[i] ^= c[j];
       c[j] ^= c[i];
       c[i] ^= c[j];
     }

     return new string(c);
   }
 }
}

 

Note that I also used multiple statements in the for-loop. (see highlighted line)

Have fun! 😉

C# Parallel Computing: Parallel.For-loop

The C# For-loop in Parallel computing looks easy. Something I will need to keep in mind when doing calculations. 😉

Here is an example in .NET 4.0:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
 class Program
 {
  static void Main(string[] args)
  {
   Parallel.For(0, 2500,
     delegate(int i)
     {
      // Do some work here
      Console.WriteLine(i);
     }
    );
   Console.ReadLine();
  }
 }
}

More information about Parallel computing in C#:

Have fun!

Renaming usings in C#

A collegue showed me something useful today: renaming namespaces/using statements in C# which may result in cleaner code.
Some simple code to demonstrate this:

using Test = System.Diagnostics;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      Test.Debug.WriteLine("Testing new using");
    }
  }
}

 

Happy coding 😉

C# float

A loop in C# using floating point numbers:

 for (float f = 16777217f; f < 16777218f; f++) { }

Why a post about this? Well find out by running this little C# Console Application:

using System;

namespace ConsoleApplication1
{
 class Program
 {
   static void Main(string[] args)
   {
     for (float f = 16777217f; f < 16777218f; f++)
       Console.WriteLine("Hello.");
   }
 }
}

What went wrong?
The value of float f is actually 16777216, because it was rounded while storing the value.

float f = 16777217f;

Let’s explain what goes wrong with the increment by showing an example:

float f = 16777217f;
f++;

We would expect that f is now 16777218. Wrong!

float f = 16777217f;
// f is now 16777216 !!
f++;
// f is still 16777216 !! (incremented by 1 but when being saved it is rounded again)

More information about floats can be found here.

Null-coalescing operator (??)

The Null-Coalesce operator (??) in C# can be very useful.

Here a some basic examples. Example2() is the refactored method of Example1() using the null-coalescing operator.

namespace ExampleCode
{
 class Program
 {
 static void Main(string[] args)
 {
 Program p = new Program();
 int result0 = p.Example0();       // result: "5"
 string result1 = p.Example1();    // result: "string3"
 string result2 = p.Example2();    // result: "string3"
 }

 private int Example0()
 {
 int? i = null;
 return i ?? 5;
 }

 private string Example1()
 {
 string s1 = null;
 string s2 = null;
 string s3 = "string3";

 if (s1 != null)
 return s1;
 else if (s2 != null)
 return s2;
 else if (s3 != null)
 return s3;
 else
 return null;
 }

 private string Example2()
 {
 string s1 = null;
 string s2 = null;
 string s3 = "string3";

 return s1 ?? s2 ?? s3;
 }
 }
}

 

Enjoy 😉

Using C# keywords in your Enums

Sometimes you want to define a value in your enumeration which has the same name as a keyword in C#.

The compiler will not like this:

The solution in C# for this is to prefix your value with the @-character:

namespace EnumTest
{
 //as = attosecond
 public enum Time : byte
 {
 s = 1,
 ms = 2,
 @as = 3
 }
}

For Visual Basic use square brackets like this [as].