Retrieve an element from List without loop [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to retrieve an element or a list of elements from my list without using for or foreach loop, the reason is my list is very big, also, I need to do another loop on the result. In this point of view, algorithmic complexity is not a good idea to use two loops inside each other.

The answer depends on the mean to determine which element you want. The fact is that a List will have on O(1) complexity if you have the index of the element you want to find; otherwise it will always have a O(n) complexity (LINQ or not).
However, if you need to extract many elements in your collection and then use a loop on them, LINQ will enable you to do it with only one loop (on all the elements of your collection) easily:
foreach (var element in myCollection.Where(myCondition))
If you want to find your element with a smaller complexity than O(n), you should look at HashSet<T> and Dictionary<TKey, TValue>.
But your question is not precise enough to give you a more specific answer.

if you can to get one element from a list without looping you can use LINQ ( first,firstOrdefault, Single,SingleOrdefault) functions that can give you one element from you list, also if you need more than once you can use where with ToList at the end for the cast.all those functions take as parameters lambda expression.
Also check those links to see why I am right:
http://www.anujvarma.com/replacing-foreach-loops-with-linq-expressionsa-performance-gain/
http://www.anujvarma.com/linq-versus-loopingperformance/
http://code-fight.club/fight/7/linq-vs-foreach
As long as you have a big size collection, LINQ is the correct choice.
You can also check this example to see why LINQ is the best choice to handle a big size array '400k elements +' :
https://dotnetfiddle.net/pxcbHY
Here is the result:
Real run:
TestLINQ count: 499854
0:00:00:00.0170207
TestForeach count: 499854
0:00:00:00.0200297
TestFor count: 499854
0:00:00:00.0198944
The difference between LINQ, For and Foreach will be visible if we use bigger arrays.

Related

What is the most efficient way to split a List into two Lists based on one condition? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I want to split a list into two seperate lists one with elements which fulfil the condition and another with elements that don't fulfil the condition.
A possible Solution would be this:
var listTrue = list.Where(x => x.condition());
var listFalse = list.Where(x => !x.condition());
But i am not just looking for a solution. I am looking for an efficient solution. I don't demand any performance metrics.
I would be happy to receive ideas and solutions. I would benchmark those and look if any of them make a significant performance gain.
I am also looking for a solution that is available in the .net framework 4.8.
Most efficient in terms of performance would be to do a foreach loop which will do it by O(n) complexity. Although I would recommend just using LINQ as you mentioned which will be O(2n) = O(n). If your list contains lots of rows and you really need the performance to be most efficient, go for it:
var listTrue = new List<...>();
var listFalse = new List<...>();
foreach (var item in list)
{
if (item.condition())
{
listTrue.Add(item);
}
else
{
listFalse.Add(item);
}
}
Note, you might do it in parallel also if it is logically make sense.

cannot convert from 'char[]' to 'string[]' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was trying to make a save dialog from a rich text document but I keep getting an error on the text.
Error:
ArgumentNullException
Argument 2: cannot convert from 'char[]' to 'string[]'
I'm new to c# so I'm not sure how to fix this.
System.IO.File.WriteAllLines(ofd.FileName.ToString(), richTextBox1.Text.ToArray());
Use a different method:
System.IO.File.WriteAllText(ofd.FileName, richTextBox1.Text);
I'd recommend avoiding to use Lines for this; it's a waste of resources to split the text into N strings only to write them all back to a combined file
Why didn't your first attempt work? WriteAllLines requires an array of strings. If you call .ToArray() on a string you get an array of characters; strings and characters are very different things.
ToArray() is a LINQ method that works because a string can be treated as an enumerable sequence of char. Typically it's very rare that you would do so and you would probably use the dedicated string.ToCharArray() method if you did want a char array from a string. Mostly I use it when splitting strings on multiple characters: someString.Split(".,?!'-/:;()".ToCharArray()); as it's more readable than putting each char separately
You're more likely to use ToArray() later on for things like filtering one array using LINQ and turning the result into an array again:
Person[] smiths = people.Where(person => person.LastName == "Smith").ToArray();
Other points:
OpenFileDialog's FileName is already a string; you don't need to ToString() it
Please get into the habit of renaming your controls after you add them to a form (top of the properties grid, the (Name) line, takes two seconds). It's a lot easier for us on the internet (and you in 3 weeks' time) to be able to read usernameTextBox and go "oh, that's the username textbox" than it is to be wondering "is it textbox56 or textbox27 that is the username? I'll just go into the form designer and check.."

Generate skipable list based on chars [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am very sure that there is a technical term for this problem, but unfortunately I do not know it.
I have an alphabetical charset and the requirement is to create the combination of all the chars with a maximum length
The idea is (sample):
Generate a collection of A, AA, AAA, AAAA, AAAAA, AAAAAA
Next: A, AB, ABA, ABAA, ABAAA
Next A, AB, ABB, ABBA, ABBAA
The reason:
We have to query an API that delivers search results.
But if I don't get search hits from the API on AAA, I don't need to search for AAAA anymore, because it can't get search hits either. I can then move on to AAB.
The question:
My problem is that I'm not sure how the code has to be built to achieve this goal. I lack the structural approach.
I've already tried nested loops, but unfortunately I don't get the result.
I also used Combination Libraries, but they focus on other problems.
Many thanks for hints!
What you're looking for is a particular data structure called a Tree, but probably more specifically in your case, a Trie.
Trie data structures are commonly used in things like Autocomplete. With the image below, if someone typed "te", I can traverse the Trie and see what options would come after that (tea, ted, ten).
It looks like this would also fit your use case from what I can tell.

Fastest way to search for terms in a text file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list of terms (words), say around 500,000, they are loaded into some data structure, like a Dictionary or Trie perhaps.
In my program I want to open each text document and search for occurrences of these terms. When i find one I want to stop and transform the string in the text file (replacing it with the transformed string), and continue searching. Once complete with the file, I write to disk the new modified file.
My questions are as follows
What would be the best data structure to use for this purpose - a Tree type structure or .NET Dictionary
How do i search the text? Do I break it up into words and compare each chunk against the list I have, or some other method like RegEx, or .NET methods like Contains()?
I'm just looking for some advice on where to start, because I think speed will be really important when I'm dealing with very large and numerous text files.
EDIT: Yes the Transformation is same for each string - based on an algorithm - so each string will look different though. (like for example using a Cipher on the word to make is unreadable. Anyway I'm just looking for someone to point me in the right direction, I'm not familiar with many algorithms and data structures out there.
From a class I took once, I remember we covered a couple of different algorithms. Here are the ones that I remembered to be pretty effective with large text files...
Boyer-Moore:
http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
Knuth-Morris-Pratt:
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
These will only help with the lookup, then you can do the manipulation yourself
A hash table (Dictionary) is going to give you faster lookups than a tree structure. A well-built hash table can find a matching word entry with two or three probes, while a tree structure may require up to an order of magnitude more comparisons.
As for splitting up the words, it would seem to be simple enough to collect all alphabetical characters (and possibly digit characters) up to the next whitespace or punctuation character for each word. You will probably want to convert each word into all-lowercase before looking it up in the dictionary.

sort list by double variable and view the 5 first [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a variable "score" in a class team. Now I need a list of teams ordered by score and a viewbag of the first 5 teams.
Anyone who can help me?
Assuming that you have a collection of teams:
ViewBag.TopFive = teams.OrderByDescending(x => x.Score).Take(5);
This is probably a learning assignment, so I will not write any code.
Since you are looking for the first five items, sorting the list may prove too expensive, especially when the list is very long. Instead, you can walk the list, and pick the top five elements.
Seed your five-element "top list" with the initial five elements of the original list, then sort the top list. Since its size is fixed, sorting its five elements is O(1). Now walk the remaining N-5 elements of the original list, comparing each item to the smallest element of the sorted "top list". If you see a value that's bigger than the smallest item of the top five list, replace one of the top items with the current item, and let the smallest item "fall off" the end of the list. This whole process is O(N), which may be a significant improvement over a sorting solution, which is O(N*logN).

Categories

Resources