SRV meets LINQ

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;
		return  minServers.First();
Leave a comment


  1. 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.

  2. yes thats correct. I have fixed this a while ago in my code, but have not updated this post.

  3. is the source code for ags xmpp available ?

  4. yes, you can find instructions for getting the source code here:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.