Henris blogg

 

c#/Linq: Remove duplicates in a list, using group and orderby in linq

I had some really ugly code to remove duplicates in a list.

Here's my take at doing the same with linq and grouping.

Probably could be improved, but I like this way better then the ugly original.

I find it really easy to read too.

Because of the way the original was constructed, I used a couple of tries to get to this.

My first attempt used the same way of thinking as the original,

and that wasn't much prettier then the old c# 2.0 code.

private static List<NytegningAktoerRetur> GetSisteTilbudPåSammeNrLinq(List<NytegningAktoerRetur> liste)

{

    var MidlertidigNrTilbud = from t in liste

                         group t by t.MidlertidigForsNr;

    var FinListe = new List<NytegningAktoerRetur>();

    foreach (var midlert in MidlertidigNrTilbud)

    {

        if (midlert.Count() > 1)

        {

            //Finn siste

            var t = from tilbud in midlert

                    orderby FinnOppgaveID(tilbud.TilbudID) descending, tilbud.DatoRegistrert descending                   

                    select tilbud;

            FinListe.Add(t.First());

        }

        else

            FinListe.Add(midlert.First());

    }

    return FinListe;

}

The original is here for warning purposes only :)

Don't try this at home…:

private static void GetSisteTilbudPåSammeNr(FinnTilbudAktoerReturMelding retur, bool InkluderStartedeTilbud)

{

    Dictionary<string, FinnTilbudHolder> liste = new Dictionary<string, FinnTilbudHolder>();

    List<string> sakstartet = new List<string>();

    FinnTilbudHolder h;

    foreach (NytegningAktoerRetur r in retur.TilbudsListe)

    {

        int OppgaveID = FinnOppgaveID(r.TilbudID);

        h = new FinnTilbudHolder();

        h.Tilbud = r;

        h.OppgaveID = OppgaveID;

        //finn nyeste

        if (liste.ContainsKey(h.Tilbud.MidlertidigForsNr))

        {

            //finn siste basert på oppgaveid

            FinnTilbudHolder org = liste[h.Tilbud.MidlertidigForsNr];

            if (OppgaveID > org.OppgaveID)

            { //denne (r) er nyest, skal erstatte org i listen

                liste[h.Tilbud.MidlertidigForsNr] = h;

            }

            else if (org.OppgaveID > OppgaveID) //org er nyest basert på oppgaveid

            {

                //beholder org

            }

            else if (org.OppgaveID == 0 && OppgaveID == 0) //ingen oppgaveid angitt, returner nyeste på dato

            {

                //hvis nyerere "vinner" den (r), ellers ingen endring

                if (h.Tilbud.DatoRegistrert > org.Tilbud.DatoRegistrert)

                    liste[h.Tilbud.MidlertidigForsNr] = h;

            }

        }

        else

        {

            liste.Add(h.Tilbud.MidlertidigForsNr, h);

        }

        //husk de som har startet sak

        if (!String.IsNullOrEmpty(h.Tilbud.Saksnr)) sakstartet.Add(h.Tilbud.MidlertidigForsNr);

    }

    if (!InkluderStartedeTilbud)

    {

        //fjern de som har startet sak

        foreach (string forsnr in sakstartet)

        {

            liste.Remove(forsnr);

        }

    }

    List<NytegningAktoerRetur> l = new List<NytegningAktoerRetur>();

    foreach (FinnTilbudHolder f in liste.Values)

    {

        l.Add(f.Tilbud);

    }

    retur.TilbudsListe.Clear();

    retur.TilbudsListe.AddRange(l.ToArray());

}

That's it for the old retarted ehh I mean retired code :)

To be fair, I also moved the code of InkluderStartedeTilbud out of this function, it goes like this:

if (!param.InkluderStartedeTilbud)

{

    //Fjern startede tilbud

    retur.TilbudsListe.RemoveAll(g => !String.IsNullOrEmpty(g.Saksnr));

}

I just moved it out to make the function more clear.

The refactoring to linq also allowed me to remove the FinnTilbudHolder class, as it was just used to keep record of each records id,

because it was an expensive operation to get it (ws call).

In addition and it was now easy to just get the id when I knew that there was more then one record with the same number.

I could (should)  have done that with the old code too, but now it was real easy to do because of the grouping and count.

I'm happy with the new and refactored linq version, and the easy grouping, counting and sorting in linq.

Rgds

HM

Comments [0]

C#/Linq : Filter a list based on From/ To dates (and IENUMERABLE to LIST)

Filter my List (retur.Tilbudsliste)

based on input of from and to-dates

if (param.FromDato > DateTime.MinValue || param.ToDate > DateTime.MinValue)

{

      //filter on date

      var filtrert =    from t in retur.TilbudsListe

                        where t.DateRegistered >= param.FromDate &&

                             (param.ToDate == DateTime.MinValue || t.DateRegistered <= param.ToDate)

                        select t;

     retur.TilbudsListe = filtrert.ToList();

}

The result filtrert is of type Ienumerable, and is then cast to a list with:

retur.TilbudsListe = filtrert.ToList();

Note that with the check on DateTime.Minvalue we've made both inputs optional,

allowing us to specify none, one or both params.

Comments [0]

Team Foundation server: policy error

When checking in to Team Foundation Server I got error:

TF10139

with several errors regarding policies, including:

Internal error in changeset comments policy

Solution:

Modify my Team Foundation Server Power Tools-installation

and select the Check-In Policy Pack

Team Foundation Server Power Tools can be downloaded from here: http://msdn.microsoft.com/en-us/teamsystem/bb980963.aspx

As I already have it installed I'm not sure if you have to select Custom etc when installing, but you should verify that this is selected when installing, or modify afterwards as I just did. :)

That's it.

Have a nice weekend.

Rgds

Henri

Comments [0]

c#: Changing a value in a dictionary in a foreach

I was trying to loop through a dictionary,

update it's value if a certain condition was met,

if not remove the item from the dictionary.

(Seems I have done something lke this before, but that's why I blog it, so I can remember next time… :))

Here's my first attempt:

        private void FindEditedFieldsNotWorking(Dictionary<string, string> dictionary, Control ctrl)

        {

            foreach (KeyValuePair<string,string> kvp in dictionary)

            {

                CheckBox c = ctrl.Controls["chk" + kvp.Key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[kvp.Key] = ctrl.Controls[kvp.Key].Text;

                }

                else

                    dictionary.Remove(kvp.Key);

            }

        }

It compiles ok and seems ok.

Might have a misgiving with removing the item in a loop, but hey it's worth a shot..

When running this I got an exception something like

"Collection was modified; enumeration operation may not execute."

My first thought was that my dictionary.Remove was the culprit, so I put a breakpoint there.

But that was not the case (although that is not supported either in this loop)

It seems that I can't actually change the freakin' value within my foreach loop…!

So I tried the same but this time using just the keys in the loop:

         private void FindEditedFieldsNotWorkingEither(Dictionary<string, string> dictionary, Control ctrl)

        {

            foreach (string Key in dictionary.Keys)

            {

                CheckBox c = ctrl.Controls["chk" + Key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[Key] = ctrl.Controls[Key].Text;

                }

                else

                    dictionary.Remove(Key);

            }

        }

Still no go, same error.

Eventually I read a little bit about this using google and found that I couldn't do any changes while enumerating.

Here are some links I used:

http://stackoverflow.com/questions/1070766/editing-dictionary-values-in-a-foreach-loop

http://stackoverflow.com/questions/1562729/why-cant-we-change-values-of-a-dictionary-while-enumerating-its-keys

Seems like a bad design decision has made this a problem for many ppl.

The incling is probably the implisit add functionality when doing dict[key]=value; when key is not existing.

Anyways we have to get around this somehow.

The solution I thought was nicest when I couldn't use the "logic" solution is:

.Net 2.0

        private void FindEditedFieldsWorking(Dictionary<string, string> dictionary, Control ctrl)

        {

            List<string> keys = new List<string>(dictionary.Keys);

            foreach (string key in keys)

            {

                CheckBox c = ctrl.Controls["chk" + key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[key] = ctrl.Controls[key].Text;

                }

                else

                    dictionary.Remove(key);

            }

        }

Almost as nice as the first version, and with the added premium that dictionary.Remove won't be a problem.

Or if you're running .Net 3.0 or higher you could just do this:

        private void FindEditedFieldsWorking(Dictionary<string, string> dictionary, Control ctrl)

        {

          

            foreach (var key in dictionary.Keys.ToList())

            {

                CheckBox c = ctrl.Controls["chk" + key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[key] = ctrl.Controls[key].Text;

                }

                else

                    dictionary.Remove(key);

            }

        }

where the ToList does the same as our 2.0 solution, namely creating a temp list to hold the keys.

Nice solution on a not so nice problem.

Hope this helps someone,

it will help me next time anyways :)

Regards

Henri Merkesdal

MERIT

Comments [0]

c#: Modal forms, ShowDialog and Close()

In first form you want to show a modal form to user, and get some object/property back from it.

You create a new form and shows it using ShowDialog()

            frmTilbud frm = new frmTilbud(t)

           frm.ShowDialog();

            …. some more code after frm is closed here

How do you get the object back to the first form?

You of course have the Dialogresult, but that's just a simple Ok/Cancel etc.

You could call methods and set properties on the first form, but then you wouldn't want/need the modal dialog.

You should think that when closing the modal form, you would also loose any properties etc on the modal form.

But this is the clue and solution:

even calling this.Close()  in the modal form does not unload it from memory

That means you can create public properties on your modal form, and check them when it's closed again

            frmTilbud frm = new frmTilbud()

           frm.ShowDialog();

            if (frm.MyProperty != null)

                        resultprop=frm.MyProperty;

            ..etc

This also means that you're modal dialog isn't disposed before you explicitly call dispose on it (or you exit your application)

So a good practice is this:

            using (frmTilbud frm = new frmTilbud())

      {

            frm.ShowDialog();

            if (frm.MyProperty != null)

                  resultprop = frm.MyProperty;

      }

This disposes the form when you're finished with the curly braces.

rgds

Henri

Comments [0]

VSS Sourcesafe automatic logon

To logon sourcesafe automaticly:

Create userenvironment

variable SSUSER value your username

the password can be specified the same way: SSPWD

spanspan

Comments [0]

June 24, 2009

sourcesafe share/branch

How to a share/branch a project in sourcesafe.

Say I have

$/Tools/MyTool/v1.0.0

in sourcesafe.

Now I want to create

$/Tools/MyTool/v2.0.0

either by sharing (links to same copy of file)  or branching (separate files, copied at branching)

Instead of doing the obvious, Rightclick v1.0.0 and select share etc here's how you do it:

1)         select the place you want the files to end, in this example

            $/Tools/MyTool

2)         rightclick and select Share to …

3)         now select your version i.e $/Tools/MyTool/v1.0.0,

            and optionally select Branch after share for a separate copy

4)         in the next dialog you can specify a name, in this example it should bee v2.0.0

            remember to select recursive

Thank MS for not being this counterintuitive usually… :)

Happy branching

span

Comments [0]

June 16, 2009

Sort List

Sort with a delegate:

Sorts a list by name/string

List<VomWS.Variabel> liste = new List<Variabel>();

liste.AddRange(samling.Liste);

liste.Sort(delegate(VomWS.Variabel v1, VomWS.Variabel v2) { return v1.Navn.CompareTo(v2.Navn); });

Sort with Comparer:

Sorts a list by date in descending order

List<OppgaveInformasjon> liste = HentOppgaverDA(oppgaveType, dato, AntDager);

liste.Sort(new OppgaveInformasjonDatoDescCompare());

    public class OppgaveInformasjonDatoDescCompare : IComparer<VOMVariabler.VomWS.OppgaveInformasjon>

    {

        public int Compare(VOMVariabler.VomWS.OppgaveInformasjon x, VOMVariabler.VomWS.OppgaveInformasjon y)

        {

            return DateTime.Compare(y.DatoRegistrert, x.DatoRegistrert);

        }

    }

Comments [0]

June 11, 2009

Mouse hourglass and back

    public partial class frmOppgaver : Form

    {

        Cursor før;

        private void SettMusHourglass()

        {

            før = this.Cursor;

            this.Cursor = Cursors.WaitCursor;

        }

        private void SettMusTilbake()

        {

            this.Cursor = før;

        }

            }

Comments [0]

June 10, 2009

delegate find

ModulSamling m = modulsamling.Find(delegate(ModulSamling ms) { return ms.ID== item.Tag; });

Instead of:

ModulSamling m=FindModul(modulsamling, item.Tag);

privat ModulSamling FindModul(List<ModulSamling list, string tag)

{

      foreach(ModulSamling m in list)

      {

            if(m.ID==tag)

                  return m;

      }

      return null;

}

Comments [0]