Question

The problem: When my program stars I create a List<myClass> myList and fill it with objects. Those objects are created with date from files. And after that I don't want to change that list nor access the files again. But I need to access that List in a lot of classes / methods

The solution I came up with: create the List<myClass> myList as a private in a static class and fill it using the constructor of my static class, and access it only with properties that return a myList.AsReadOnly(). This way I can't change the actual list. But the return of the AsReadOnly is a IList, right? I was checking the IList on MSDN and there's no BinarySearch method... Which would make the whole thing quite slow.

How can I solve this issue? Copying the IList return to a normal List so I can sort and BinarySearch it? Or maybe change the whole "myList.AsReadOnly()" approach? I'm open to all kinds of suggestions and approaches ^^ Changing the whole code is not a problem.

edit:

  1. TL;DR how can I make a "global" List that can be access by any method / class in my program, that can be sorted using the List.Sort method, that can be binarysearched AND that can't have it's contents altered (neither by adding nor removing elements) after it was created.
  2. As soon as I get back home I'll post some code.
Was it helpful?

Solution 2

In this case, depends on personal preference. This is mine, as an example:

private List<string> _MyList = new List<string>();

private void InitializeList()
{
    //code here to fill list.

    //Keep in mind, that binary search works on sorted lists.
    _MyList.Sort(/* Place your object comparer here.  */);
}



//Make a copy in an array.
public string[] MyListAsArray
{
    get { return _MyList.ToArray(); }
}


public int GetBinarySearchIndex(string value)
{
    return Array.BinarySearch(MyListAsArray, value/*, Place your object comparer here.  */);
}

OTHER TIPS

If you are using later versions of .Net, instead of using AsReadOnly(), use an ImmutableList<T>. It cannot be modified once created but has the BinarySearch() method you are looking for. It is also potentially more efficient if you want to subdivide the list or access it from multiple threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top