LINQ (Language Integrated Query) is really amazing.
Today I rewrote a function which picks the correct SRV-Record according to the priority and weight for XMPP client and server connections. The old code without comments were 63 lines. The new code is about 12 lines and much easier to read IMHO.
But take a look at the code yourself.
private SRVRecord PickSRVRecord(List<Srvrecord> srv) { IEnumerable<Srvrecord> minServers = srv.Where(s1 = t; s1.Priority == srv.Min(s => s.Priority)); if (minServers.Count() > 1) { int sumWeight = minServers.Sum(s = s.Weight); // Create a random value between 1 - total Weight int rnd = new Random().Next(1, sumWeight); int count = 0; SRVRecord result = minServers.First( s => rnd > ((count += s.Weight) - s.Weight) && rnd <= count); return result; } else return minServers.First(); }
you might consider caching the return value of
srv.Min(s => s.Priority)
so it doesn’t reevaluate that repeatedly.
also, I don’t know if your minServers is guaranteed to have at least one item. if it could possibly have 0, then you should return .FirstOrDefault() to get a null value when there isn’t a “First” item.
linq rocks.
oh, and thanks for an excellent xmpp library.
yes thats correct. I have fixed this a while ago in my code, but have not updated this post.
is the source code for ags xmpp available ?
yes, you can find instructions for getting the source code here:
http://www.ag-software.de/agsxmpp-sdk/download/