Evgeni Velikov
Evgeni Velikov

Reputation: 382

How can find specific HashSet elements with linq

I have HashSet of array of strings. One string of array is like "2015-9-14 21:22:13" DateTime. How can convert with DateTime.ParseExact to be dateTime and then find all times from HashSet arrays between two dateTimes using linq. Before I used list but HashSet is have better performance when is search element, and now I change my code to work with HashSet.

Here is my old code with list:

foreach (var infos in this.InfoFromDatabase)
        {
            thisTime = DateTime.ParseExact(infos[5], "yyyy-M-d H:m:s", null);

            // if is in this diapazon time add in list
            if (thisTime > minimumDateTime && thisTime < maximumDateTime)
            {
                allInformation.Add(infos);
            }
        }

Upvotes: 0

Views: 5271

Answers (2)

Nico Schertler
Nico Schertler

Reputation: 32627

If you're just looking for the LINQ, then here it is. It works with any IEnumerable<string[]> (both hash set and list):

//Assuming that 
//IEnumerable<string[]> this.InfoFromDatabase

var allInformation = this.InfoFromDatabase.Where(i =>
{
    var thisTime = DateTime.ParseExact(i[5], "yyyy-M-d H:m:s", null);
    return thisTime > minimumDateTime && thisTime < maximumDateTime;
});

You may call ToList() or any other To...() method on the result if you need.

Upvotes: 0

Oliver
Oliver

Reputation: 45119

A HashSet makes only sense if you need to check for exact that element (or better: with the same value returned by GetHashCode()). In your case you just search through all the data and it is only available in raw string blocks. So a hash set won't give you any performance improvements.

Due to the fact that you named your variable InfoFromDatabase and you know you have to parse element five from the array as date time, there seems to be a structure within each array. So maybe you should create a class containing individual properties for each element in the array and which will get such an array within the constructor. Here you could parse the array and fill up the properties. Now you can fill up a list with your objects and easily check the values if they match your criteria.

Unfortunately by building up such structures in memory there isn't much you can do to improve performance (maybe lazily initialize the property values from the given array), but I would skip such optimizations till you measured a performance bottleneck. In that case come back with your concrete performance problem and SO will surely help you to solve it.

Upvotes: 1

Related Questions