<p>I am looking for a very fast way to filter down a collection in C#.  I am currently using generic <code>List&lt;object&gt;</code> collections, but am open to using other structures if they perform better.</p>
<p>Currently, I am just creating a new <code>List&lt;object&gt;</code> and looping thru the original list.  If the filtering criteria matches, I put a copy into the new list.</p>
<p>Is there a better way to do this?  Is there a way to filter in place so there is no temporary list required?</p>

[{'answer_id': 26203, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 9, 'selected': True, 'text': '<p>If you\'re using C# 3.0 you can use linq, which is way better and way more elegant:</p>\n<pre class="lang-c# prettyprint-override"><code>List&lt;int&gt; myList = GetListOfIntsFromSomewhere();\n\n// This will filter ints that are not &gt; 7 out of the list; Where returns an\n// IEnumerable&lt;T&gt;, so call ToList to convert back to a List&lt;T&gt;.\nList&lt;int&gt; filteredList = myList.Where(x =&gt; x &gt; 7).ToList();\n</code></pre>\n<p>If you can\'t find the <code>.Where</code>, that means you need to import <code>using System.Linq;</code> at the top of your file.</p>\n'}, {'answer_id': 26206, 'author': 'Mykroft', 'author_id': 2191, 'author_profile': 'https://Stackoverflow.com/users/2191', 'pm_score': 4, 'selected': False, 'text': '<p><code>List&lt;T&gt;</code> has a <code>FindAll</code> method that will do the filtering for you and return a subset of the list. </p>\n\n<p>MSDN has a great code example here: <a href="http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx</a></p>\n\n<p>EDIT: I wrote this before I had a good understanding of LINQ and the <code>Where()</code> method. If I were to write this today i would probably use the method Jorge mentions above. The <code>FindAll</code> method still works if you\'re stuck in a .NET 2.0 environment though.</p>\n'}, {'answer_id': 26209, 'author': 'Adam Haile', 'author_id': 194, 'author_profile': 'https://Stackoverflow.com/users/194', 'pm_score': 2, 'selected': False, 'text': '<p>To do it in place, you can use the RemoveAll method of the "List&lt;>" class along with a custom "Predicate" class...but all that does is clean up the code... under the hood it\'s doing the same thing you are...but yes, it does it in place, so you do same the temp list.</p>\n'}, {'answer_id': 26210, 'author': 'Serhat Ozgel', 'author_id': 31505, 'author_profile': 'https://Stackoverflow.com/users/31505', 'pm_score': 3, 'selected': False, 'text': '<p>You can use IEnumerable to eliminate the need of a temp list.</p>\n\n<pre><code>public IEnumerable&lt;T&gt; GetFilteredItems(IEnumerable&lt;T&gt; collection)\n{\n    foreach (T item in collection)\n    if (Matches&lt;T&gt;(item))\n    {\n        yield return item;\n    }\n}\n</code></pre>\n\n<p>where Matches is the name of your filter method. And you can use this like:</p>\n\n<pre><code>IEnumerable&lt;MyType&gt; filteredItems = GetFilteredItems(myList);\nforeach (MyType item in filteredItems)\n{\n    // do sth with your filtered items\n}\n</code></pre>\n\n<p>This will call GetFilteredItems function when needed and in some cases that you do not use all items in the filtered collection, it may provide some good performance gain.</p>\n'}, {'answer_id': 26211, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/fh1w7y8z.aspx" rel="nofollow noreferrer">FindAll</a> method of the List, providing a delegate to filter on.  Though, I agree with @<a href="https://stackoverflow.com/questions/26196/filtering-collections-in-c#26201">IainMH</a> that it\'s not worth worrying yourself too much unless it\'s a huge list.</p>\n'}, {'answer_id': 26232, 'author': 'Tom Lokhorst', 'author_id': 2597, 'author_profile': 'https://Stackoverflow.com/users/2597', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <blockquote>\n    <p>If you're using C# 3.0 you can use linq</p>\n  </blockquote>\n</blockquote>\n\n<p>Or, if you prefer, use the special query syntax provided by the C# 3 compiler:</p>\n\n<pre><code>var filteredList = from x in myList\n                   where x &gt; 7\n                   select x;\n</code></pre>\n"}, {'answer_id': 26273, 'author': 'Jon Erickson', 'author_id': 1950, 'author_profile': 'https://Stackoverflow.com/users/1950', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a code block / example of some list filtering using three different methods that I put together to show Lambdas and LINQ based list filtering.</p>\n\n<pre><code>#region List Filtering\n\nstatic void Main(string[] args)\n{\n    ListFiltering();\n    Console.ReadLine();\n}\n\nprivate static void ListFiltering()\n{\n    var PersonList = new List&lt;Person&gt;();\n\n    PersonList.Add(new Person() { Age = 23, Name = "Jon", Gender = "M" }); //Non-Constructor Object Property Initialization\n    PersonList.Add(new Person() { Age = 24, Name = "Jack", Gender = "M" });\n    PersonList.Add(new Person() { Age = 29, Name = "Billy", Gender = "M" });\n\n    PersonList.Add(new Person() { Age = 33, Name = "Bob", Gender = "M" });\n    PersonList.Add(new Person() { Age = 45, Name = "Frank", Gender = "M" });\n\n    PersonList.Add(new Person() { Age = 24, Name = "Anna", Gender = "F" });\n    PersonList.Add(new Person() { Age = 29, Name = "Sue", Gender = "F" });\n    PersonList.Add(new Person() { Age = 35, Name = "Sally", Gender = "F" });\n    PersonList.Add(new Person() { Age = 36, Name = "Jane", Gender = "F" });\n    PersonList.Add(new Person() { Age = 42, Name = "Jill", Gender = "F" });\n\n    //Logic: Show me all males that are less than 30 years old.\n\n    Console.WriteLine("");\n    //Iterative Method\n    Console.WriteLine("List Filter Normal Way:");\n    foreach (var p in PersonList)\n        if (p.Gender == "M" &amp;&amp; p.Age &lt; 30)\n            Console.WriteLine(p.Name + " is " + p.Age);\n\n    Console.WriteLine("");\n    //Lambda Filter Method\n    Console.WriteLine("List Filter Lambda Way");\n    foreach (var p in PersonList.Where(p =&gt; (p.Gender == "M" &amp;&amp; p.Age &lt; 30))) //.Where is an extension method\n        Console.WriteLine(p.Name + " is " + p.Age);\n\n    Console.WriteLine("");\n    //LINQ Query Method\n    Console.WriteLine("List Filter LINQ Way:");\n    foreach (var v in from p in PersonList\n                      where p.Gender == "M" &amp;&amp; p.Age &lt; 30\n                      select new { p.Name, p.Age })\n        Console.WriteLine(v.Name + " is " + v.Age);\n}\n\nprivate class Person\n{\n    public Person() { }\n    public int Age { get; set; }\n    public string Name { get; set; }\n    public string Gender { get; set; }\n}\n\n#endregion\n</code></pre>\n'}, {'answer_id': 3916043, 'author': 'gouldos', 'author_id': 449696, 'author_profile': 'https://Stackoverflow.com/users/449696', 'pm_score': 2, 'selected': False, 'text': '<p>Using LINQ is relatively much slower than using a predicate supplied to the Lists <code>FindAll</code> method. Also be careful with LINQ as the enumeration of the <code>list</code> is not actually executed until you access the result. This can mean that, when you think you have created a filtered list, the content may differ to what you expected when you actually read it.</p>\n'}, {'answer_id': 38121663, 'author': 'Daniel Roberts', 'author_id': 3466633, 'author_profile': 'https://Stackoverflow.com/users/3466633', 'pm_score': 1, 'selected': False, 'text': '<p>If your list is very big and you are filtering repeatedly - you can sort the original list on the filter attribute, binary search to find the start and end points.</p>\n\n<p>Initial time O(n*log(n)) then O(log(n)).</p>\n\n<p>Standard filtering will take O(n) each time.</p>\n'}]
['https://Stackoverflow.com/questions/26196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2470/']