CodeCopy

November 5, 2009

How to remove objects from generic List by property value

Filed under: c# — sterndorff @ 23:59
Tags: , ,

Having two generic lists of type List<MyClass>, how do I remove from List1 all the instances of List2, matching a property?

This is the setup. I have a class:

public class MyClass
{
    public int MyValue { get; set; }
    public int MyOtherValue { get; set; }
}

And two lists:

List<MyClass> list1 = new List<MyClass>();
list1.Add(new MyClass() { MyValue = 1, MyOtherValue = 10 });
list1.Add(new MyClass() { MyValue = 2, MyOtherValue = 20 });
list1.Add(new MyClass() { MyValue = 3, MyOtherValue = 30 });
list1.Add(new MyClass() { MyValue = 4, MyOtherValue = 40 });

List<MyClass> list2 = new List<MyClass>();
list2.Add(new MyClass() { MyValue = 2, MyOtherValue = 50 });
list2.Add(new MyClass() { MyValue = 3, MyOtherValue = 60 });

I want to remove all list2 instances from list1 matching on MyValue property.

(more…)

October 13, 2009

WCF selfhosting helper

Filed under: c#,wpf — sterndorff @ 16:28
Tags: ,

A simple wrapper for hosting wcf services that works with both service references and web references.

WcfServiceHelper.Instance.StartService<MyService, IMyService>(new ServerConf());

More can be done in terms of configuration and a StopService method is missing. That is left for the reader (or untill I need it in my app).

(more…)

Selfhosting WCF on win2008

Filed under: c#,wcf — sterndorff @ 13:41
Tags: ,

If you host a WCF service as a non-administrator user on Windows 2008 (and Vista) you may get this error even if you are member of the admin groups:

HTTP could not register URL http://+:8000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details)

Solution: Log in as administrator and fire:

netsh http add urlacl url=http://+:8000/ user=DOMAIN\UserName

October 7, 2009

Rotate Zune HD screen to landscape

Filed under: c# — mazzoo @ 22:25
Tags: ,

When developing applications for the Zune HD, you might need to be able to rotate your display to landscape mode. To achieve this easily just make a Pre and Post Draw action ( BeginDraw and EndDraw ), where you manipulate the Viewport. This way you can develop the entire program in horizotal and then rotate it afterwards.

public class LandscapeZuneGame : Game
{
   private RenderTarget2D renderTarget;
   private SpriteBatch spriteBatch;

   public LandscapeZuneGame()
   {
      new GraphicsDeviceManager(this)
      {
         PreferredBackBufferWidth = 480,
         PreferredBackBufferHeight = 272
      };

      IsMouseVisible = true;
   }
   
   protected override void LoadContent()
   {
      renderTarget = new RenderTarget2D(GraphicsDevice, 480, 272, 1, SurfaceFormat.Color);
      spriteBatch = new SpriteBatch(GraphicsDevice);
      base.LoadContent();
   }

   // override BeginDraw so we can set the render target and Viewport before
   // any game drawing occurs.
   protected override bool BeginDraw()
   {
      if (base.BeginDraw())
      {
         GraphicsDevice.SetRenderTarget(0, renderTarget);
         GraphicsDevice.Viewport = new Viewport
         {
            X = 0,
            Y = 0,
            Width = 480,
            Height = 272,
            MinDepth = GraphicsDevice.Viewport.MinDepth,
            MaxDepth = GraphicsDevice.Viewport.MaxDepth
         };
         return true;
      }
      return false;
   }

   // override EndDraw to handle unsetting the render target, resetting the Viewport,
   // and drawing the render target's contents to the screen
   protected override void EndDraw()
   {
      GraphicsDevice.SetRenderTarget(0, null);
      GraphicsDevice.Viewport = new Viewport
      {
         X = 0,
         Y = 0,
         Width = 272,
         Height = 480,
         MinDepth = GraphicsDevice.Viewport.MinDepth,
         MaxDepth = GraphicsDevice.Viewport.MaxDepth
      };

      GraphicsDevice.Clear(Color.Black);
      spriteBatch.Begin();
      spriteBatch.Draw(
         renderTarget.GetTexture(),
         new Vector2(136f, 240f),
         null,
         Color.White,
         MathHelper.PiOver2,
         new Vector2(240f, 136f),
         1f,
         SpriteEffects.None,
         0);

      spriteBatch.End();
      base.EndDraw();
   }
}

Thanks to Nick Gravelyn for the great and easy solution

October 6, 2009

WPF Databinding Enum with nice descriptions

Filed under: c#,wpf — sterndorff @ 17:28
Tags: , , ,

I have an Enum that I want to databind to a wpf drop down box. But I want to represent the enum with some nice descriptions instead of Enum.ToString().

1) The enum with the nice descriptions: MyEnum.cs

    public enum MyEnum
    {
        [Description("Default value")] // Default value if enum is nullable and used in databinding
        DefaultValue,
        [Description("Value1 description")]
        Value1,
        [Description("Value2 description")]
        Value2
    }

(more…)

October 4, 2009

Method with a variable number of parameters

Filed under: c# — mazzoo @ 21:44
Tags: ,

When you need to create a method that handles an undefined number of parameters, one way to define it is by using an Array or list. Like this:

private void Method( string[] arguments )
{
    //...
}

This, however, have a semantic inconvenience when called:

Method( new string[] {  “a”, “b”, “c” };

To overcome this, use params before the string[] identifier, like this

private void Method( params string[] arguments )
{
    //...
}

Now you can call the Method a bit cleaner, making your code more readable:

Method(“a”, ”b”, ”c”);

September 28, 2009

Find index in list of objects

Filed under: c# — sterndorff @ 17:27
Tags: , ,

If you have an object in a list of these objects, you can find the index of the list by:

int index = listOfObjects.IndexOf(testObject);

But that only goes if the testObject reference is in the listOfObjects. If the object is not in the list, but you want to find the index based on a property, do this:

List<myObject> listOfObjects = new List<myObject>();
listOfObjects.Add(new myObject() { Name = "obj 1" });
listOfObjects.Add(new myObject() { Name = "obj 2" });

myObject testObject = new myObject() { Name= "obj 1"};

int index = listOfObjects.Select((s, i) => new { S = s, Index = i }).Where(i => i.S.Name == testObject.Name).First().Index;

Of cause you have to be shure that the testObject is in the list or you will get a exception.

September 24, 2009

Converting Nullable<int> to Nullable<Enum>

Filed under: c# — mazzoo @ 13:06
Tags: , , ,

Here is an example on how you identify a Nullable enum and convert an Nullable<int> (int? ) to Nullable<Enum> ( Enum? ).


// type = typeof(MyEnum);

if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    if (type.GetGenericArguments().Length > 0 && type.GetGenericArguments()[0].IsEnum)
    {
        int? intValue = 1;
        if (intValue.HasValue)
        {
            TypeConverter convert = TypeDescriptor.GetConverter(type);
            return convert.ConvertFrom(intValue.Value + "");
        }
        return null;
    }
}

September 18, 2009

“Casting” list to observablecollection

Filed under: c#,wpf — sterndorff @ 11:04
Tags: , , ,

Easy as pie without for loops:

List<string> myList = new List<string>();
ObservableCollection<string> myObs = new ObservableCollection<string>();

myList.ForEach(i => myObs.Add(i));

LINQ MADNESS !!

Filed under: c# — mazzoo @ 08:17
Tags: , ,

Get a list over CountryName doubles in a list of Countries.

List<CountryInfo> test = (from cX in countryInfoList
                        from cY in countryInfoList
                        where cX != cY && cX.CountryName.ToLower() == cY.CountryName.ToLower()
                        select cX ).ToList();

This is almost too simple :)

Technorati Tags: ,,
Next Page »

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.