Highest voted questions tagged .net - Stack Overflow most recent 30 from stackoverflow.com 2021-10-04T10:54:02Z https://stackoverflow.com/feeds/tag?tagnames=.net&sort=votes https://creativecommons.org/licenses/by-sa/4.0/rdf https://stackoverflow.com/q/7074 7019 What is the difference between String and string in C#? Lance Fisher https://stackoverflow.com/users/571 2008-08-10T07:18:02Z 2021-08-25T18:37:40Z <p>Example (<em>note the case</em>):</p> <pre class="lang-cs prettyprint-override"><code>string s = "Hello world!"; String s = "Hello world!"; </code></pre> <p>What are the guidelines for the use of each? And what are the differences?</p> https://stackoverflow.com/q/105372 4076 How to enumerate an enum Ian Boyd https://stackoverflow.com/users/12597 2008-09-19T20:34:50Z 2021-08-26T09:49:31Z <p>How can you enumerate an <code>enum</code> in C#?</p> <p>E.g. the following code does not compile:</p> <pre class="lang-cs prettyprint-override"><code>public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } </code></pre> <p>And it gives the following compile-time error:</p> <blockquote> <p>'Suit' is a 'type' but is used like a 'variable'</p> </blockquote> <p>It fails on the <code>Suit</code> keyword, the second one.</p> https://stackoverflow.com/q/247621 2717 What are the correct version numbers for C#? Jon Skeet https://stackoverflow.com/users/22656 2008-10-29T17:09:40Z 2021-09-02T05:58:53Z <p>What are the correct version numbers for C#? What came out when? Why can't I find any answers about <strong><em>C# 3.5</em></strong>?</p> <p>This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. <strong><em>C# 3.5</em></strong>. The hope is that anyone failing to find an answer with the wrong version number will find <em>this</em> question and then search again with the right version number.</p> https://stackoverflow.com/q/78536 2422 Deep cloning objects NakedBrunch https://stackoverflow.com/users/3742 2008-09-17T00:06:27Z 2021-09-16T16:05:28Z <p>I want to do something like:</p> <pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); </code></pre> <p>And then make changes to the new object that are not reflected in the original object.</p> <p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p> <p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p> https://stackoverflow.com/q/136035 2359 Catch multiple exceptions at once? Michael Stum https://stackoverflow.com/users/91 2008-09-25T20:56:08Z 2021-10-01T14:32:54Z <p>It is discouraged to simply catch <code>System.Exception</code>. Instead, only the &quot;known&quot; exceptions should be caught.</p> <p>Now, this sometimes leads to unnecessary repetitive code, for example:</p> <pre><code>try { WebId = new Guid(queryString[&quot;web&quot;]); } catch (FormatException) { WebId = Guid.Empty; } catch (OverflowException) { WebId = Guid.Empty; } </code></pre> <p>I wonder: Is there a way to catch both exceptions and only call the <code>WebId = Guid.Empty</code> call once?</p> <p>The given example is rather simple, as it's only a <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer"><code>GUID</code></a>. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to &quot;reset&quot; the <code>object</code>. However, if there is an unexpected exception, I still want to throw that higher.</p> https://stackoverflow.com/q/472906 2285 How do I get a consistent byte representation of strings in C# without manually specifying an encoding? Agnel Kurian https://stackoverflow.com/users/45603 2009-01-23T13:39:54Z 2020-12-09T12:18:28Z <p>How do I convert a <code>string</code> to a <code>byte[]</code> in .NET (C#) without manually specifying a specific encoding?</p> <p>I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.</p> <p>Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?</p> https://stackoverflow.com/q/618535 2241 Difference between decimal, float and double in .NET? Tom https://stackoverflow.com/users/0 2009-03-06T11:31:23Z 2020-12-24T01:29:27Z <p>What is the difference between <code>decimal</code>, <code>float</code> and <code>double</code> in .NET?</p> <p>When would someone use one of these?</p> https://stackoverflow.com/q/125319 2236 Should 'using' directives be inside or outside the namespace? benPearce https://stackoverflow.com/users/4490 2008-09-24T03:49:50Z 2020-07-31T13:48:21Z <p>I have been running <a href="http://en.wikipedia.org/wiki/StyleCop" rel="noreferrer">StyleCop</a> over some C# code, and it keeps reporting that my <code>using</code> directives should be inside the namespace.</p> <p>Is there a technical reason for putting the <code>using</code> directives inside instead of outside the namespace?</p> https://stackoverflow.com/q/9 2052 How do I calculate someone's age based on a DateTime type birthday? Jeff Atwood https://stackoverflow.com/users/1 2008-07-31T23:40:59Z 2021-09-24T16:38:57Z <p>Given a <code>DateTime</code> representing a person's birthday, how do I calculate their age in years?</p> https://stackoverflow.com/q/151005 2025 How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office? mistrmark https://stackoverflow.com/users/19242 2008-09-29T22:30:28Z 2021-10-01T07:18:39Z <p>How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?</p> https://stackoverflow.com/q/4660142 1873 What is a NullReferenceException, and how do I fix it? John Saunders https://stackoverflow.com/users/76337 2011-01-11T16:48:29Z 2021-04-05T14:05:13Z <p>I have some code and when it executes, it throws a <code>NullReferenceException</code>, saying:</p> <blockquote> <p>Object reference not set to an instance of an object.</p> </blockquote> <p>What does this mean, and what can I do to fix this error?</p> https://stackoverflow.com/q/2155930 1808 How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning? Instance Hunter https://stackoverflow.com/users/65393 2010-01-28T16:09:10Z 2021-08-14T01:17:10Z <p>A C# desktop application on the express edition worked, but then it didn't work 5 seconds later.</p> <p>I tried the following:</p> <ul> <li>Ensure debug configuration, debug flag, and full debug information are set on all assemblies.</li> <li>Delete all bin and obj folders and all DLL files related to the project from my entire machine.</li> <li>Recreate projects causing the problem from scratch.</li> <li>Reboot.</li> </ul> <p>I have two Windows Forms projects in the solution. One of them loads the debug information, one doesn't. They both refer to the assembly I'm trying to get debug information on in exactly the same way in the project file. Any ideas?</p> <hr> <p>I want to add here, mostly for myself when I come back to review this question, that symbols are not loaded until the assembly is loaded, and the assembly is not loaded until it is needed. If the breakpoint is in a library that is only used in one function in your main assembly, the symbols will not be loaded (and it will show the breakpoint as not being hit) until that function is called.</p> https://stackoverflow.com/q/538060 1770 Proper use of the IDisposable interface cwick https://stackoverflow.com/users/4828 2009-02-11T18:12:41Z 2021-07-02T01:28:12Z <p>I know from reading <a href="https://docs.microsoft.com/dotnet/api/system.idisposable" rel="noreferrer">the Microsoft documentation</a> that the "primary" use of the <code>IDisposable</code> interface is to clean up unmanaged resources.</p> <p>To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the <code>Dispose()</code> method is implemented to free <em>managed</em> resources, which seems redundant to me, since the garbage collector should take care of that for you.</p> <p>For example:</p> <pre><code>public class MyCollection : IDisposable { private List&lt;String&gt; _theList = new List&lt;String&gt;(); private Dictionary&lt;String, Point&gt; _theDict = new Dictionary&lt;String, Point&gt;(); // Die, clear it up! (free unmanaged resources) public void Dispose() { _theList.clear(); _theDict.clear(); _theList = null; _theDict = null; } </code></pre> <p>My question is, does this make the garbage collector free memory used by <code>MyCollection</code> any faster than it normally would?</p> <p><strong>edit</strong>: So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps. But suppose that <code>_theList</code> in the above code contained a million strings, and you wanted to free that memory <em>now</em>, rather than waiting for the garbage collector. Would the above code accomplish that?</p> https://stackoverflow.com/q/12051 1682 Calling the base constructor in C# lomaxx https://stackoverflow.com/users/493 2008-08-15T07:39:23Z 2021-09-02T09:52:24Z <p>If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?</p> <p>For example, if I inherit from the Exception class I want to do something like this:</p> <pre><code>class MyExceptionClass : Exception { public MyExceptionClass(string message, string extraInfo) { //This is where it's all falling apart base(message); } } </code></pre> <p>Basically what I want is to be able to pass the string message to the base Exception class.</p> https://stackoverflow.com/q/972307 1612 How to loop through all enum values in C#? [duplicate] divinci https://stackoverflow.com/users/105685 2009-06-09T20:25:04Z 2019-03-10T00:47:03Z <blockquote> <p><strong>This question already has an answer here:</strong><br> <a href="https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum">How do I enumerate an enum in C#?</a> <em>26 answers</em></p> </blockquote> <pre><code>public enum Foos { A, B, C } </code></pre> <p>Is there a way to loop through the possible values of <code>Foos</code>?</p> <p>Basically?</p> <pre><code>foreach(Foo in Foos) </code></pre> https://stackoverflow.com/q/8928403 1572 Try-catch speeding up my code? Eren Ersönmez https://stackoverflow.com/users/201088 2012-01-19T15:10:57Z 2020-11-27T14:27:10Z <p>I wrote some code for testing the impact of try-catch, but seeing some surprising results.</p> <pre><code>static void Main(string[] args) { Thread.CurrentThread.Priority = ThreadPriority.Highest; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime; long start = 0, stop = 0, elapsed = 0; double avg = 0.0; long temp = Fibo(1); for (int i = 1; i &lt; 100000000; i++) { start = Stopwatch.GetTimestamp(); temp = Fibo(100); stop = Stopwatch.GetTimestamp(); elapsed = stop - start; avg = avg + ((double)elapsed - avg) / i; } Console.WriteLine("Elapsed: " + avg); Console.ReadKey(); } static long Fibo(int n) { long n1 = 0, n2 = 1, fibo = 0; n++; for (int i = 1; i &lt; n; i++) { n1 = n2; n2 = fibo; fibo = n1 + n2; } return fibo; } </code></pre> <p>On my computer, this consistently prints out a value around 0.96..</p> <p>When I wrap the for loop inside Fibo() with a try-catch block like this:</p> <pre><code>static long Fibo(int n) { long n1 = 0, n2 = 1, fibo = 0; n++; try { for (int i = 1; i &lt; n; i++) { n1 = n2; n2 = fibo; fibo = n1 + n2; } } catch {} return fibo; } </code></pre> <p>Now it consistently prints out 0.69... -- it actually runs faster! But why?</p> <p>Note: I compiled this using the Release configuration and directly ran the EXE file (outside Visual Studio).</p> <p>EDIT: <a href="https://stackoverflow.com/a/8928476/282110">Jon Skeet's <em>excellent</em> analysis</a> shows that try-catch is somehow causing the x86 CLR to use the CPU registers in a more favorable way in this specific case (and I think we're yet to understand why). I confirmed Jon's finding that x64 CLR doesn't have this difference, and that it was faster than the x86 CLR. I also tested using <code>int</code> types inside the Fibo method instead of <code>long</code> types, and then the x86 CLR was as equally fast as the x64 CLR.</p> <hr> <p><strong>UPDATE:</strong> It looks like this issue has been fixed by Roslyn. Same machine, same CLR version -- the issue remains as above when compiled with VS 2013, but the problem goes away when compiled with VS 2015. </p> https://stackoverflow.com/q/263400 1560 What is the best algorithm for overriding GetHashCode? bitbonk https://stackoverflow.com/users/4227 2008-11-04T20:53:19Z 2021-08-05T16:59:44Z <p>In .NET, the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode" rel="noreferrer"><code>GetHashCode</code> method</a> is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.</p> <p>Is there a standard algorithm or best practice on how to implement <code>GetHashCode</code> for my custom classes so I don't degrade performance?</p> https://stackoverflow.com/q/21692193 1551 Why not inherit from List<T>? Superbest https://stackoverflow.com/users/1042555 2014-02-11T03:01:36Z 2021-05-27T07:39:56Z <p>When planning out my programs, I often start with a chain of thought like so:</p> <blockquote> <p>A football team is just a list of football players. Therefore, I should represent it with:</p> <pre><code>var football_team = new List&lt;FootballPlayer&gt;(); </code></pre> <p>The ordering of this list represent the order in which the players are listed in the roster.</p> </blockquote> <p>But I realize later that teams also have other properties, besides the mere list of players, that must be recorded. For example, the running total of scores this season, the current budget, the uniform colors, a <code>string</code> representing the name of the team, etc..</p> <p>So then I think:</p> <blockquote> <p>Okay, a football team is just like a list of players, but additionally, it has a name (a <code>string</code>) and a running total of scores (an <code>int</code>). .NET does not provide a class for storing football teams, so I will make my own class. The most similar and relevant existing structure is <code>List&lt;FootballPlayer&gt;</code>, so I will inherit from it:</p> <pre><code>class FootballTeam : List&lt;FootballPlayer&gt; { public string TeamName; public int RunningTotal } </code></pre> </blockquote> <p>But it turns out that <a href="https://stackoverflow.com/a/5376343/1042555">a guideline says you shouldn't inherit from <code>List&lt;T&gt;</code></a>. I'm thoroughly confused by this guideline in two respects.</p> <h2>Why not?</h2> <p>Apparently <a href="https://stackoverflow.com/a/5376358/1042555"><code>List</code> is somehow optimized for performance</a>. How so? What performance problems will I cause if I extend <code>List</code>? What exactly will break?</p> <p>Another reason I've seen is that <code>List</code> is provided by Microsoft, and I have no control over it, so <a href="https://stackoverflow.com/questions/5376203/inherit-listt#comment6077237_5376343">I cannot change it later, after exposing a "public API"</a>. But I struggle to understand this. What is a public API and why should I care? If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from <code>List</code> <em>and</em> it turns out I need a public API, what difficulties will I have?</p> <p>Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?</p> <p>And lastly, if Microsoft did not want me to inherit from <code>List</code>, why didn't they make the class <code>sealed</code>?</p> <h2>What else am I supposed to use?</h2> <p>Apparently, for custom collections, Microsoft has provided a <code>Collection</code> class which should be extended instead of <code>List</code>. But this class is very bare, and does not have many useful things, <a href="https://stackoverflow.com/questions/1474863/addrange-to-a-collection">such as <code>AddRange</code></a>, for instance. <a href="https://stackoverflow.com/a/12039943/1042555">jvitor83's answer</a> provides a performance rationale for that particular method, but how is a slow <code>AddRange</code> not better than no <code>AddRange</code>?</p> <p>Inheriting from <code>Collection</code> is way more work than inheriting from <code>List</code>, and I see no benefit. Surely Microsoft wouldn't tell me to do extra work for no reason, so I can't help feeling like I am somehow misunderstanding something, and inheriting <code>Collection</code> is actually not the right solution for my problem.</p> <p>I've seen suggestions such as implementing <code>IList</code>. Just no. This is dozens of lines of boilerplate code which gains me nothing.</p> <p>Lastly, some suggest wrapping the <code>List</code> in something: </p> <pre><code>class FootballTeam { public List&lt;FootballPlayer&gt; Players; } </code></pre> <p>There are two problems with this:</p> <ol> <li><p>It makes my code needlessly verbose. I must now call <code>my_team.Players.Count</code> instead of just <code>my_team.Count</code>. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal <code>List</code>... But that's a lot of code! What do I get for all that work?</p></li> <li><p>It just plain doesn't make any sense. A football team doesn't "have" a list of players. It <em>is</em> the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.</p></li> </ol> <p>I realize that what happens "under the hood" can be said to be "adding X to Y's internal list", but this seems like a very counter-intuitive way of thinking about the world.</p> <h2>My question (summarized)</h2> <p>What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a <code>list</code> of <code>things</code> with a few bells and whistles?</p> <p>Is inheriting from <code>List&lt;T&gt;</code> always unacceptable? When is it acceptable? Why/why not? What must a programmer consider, when deciding whether to inherit from <code>List&lt;T&gt;</code> or not?</p> https://stackoverflow.com/q/55984 1515 What is the difference between const and readonly in C#? readonly https://stackoverflow.com/users/4883 2008-09-11T08:02:19Z 2021-04-24T16:11:04Z <p>What is the difference between <strong><code>const</code></strong> and <strong><code>readonly</code></strong> in C#? </p> <p>When would you use one over the other?</p> https://stackoverflow.com/q/661561 1502 How do I update the GUI from another thread? CruelIO https://stackoverflow.com/users/36476 2009-03-19T09:37:40Z 2020-02-28T12:29:30Z <p>Which is the simplest way to update a <code>Label</code> from another <code>Thread</code>?</p> <ul> <li><p>I have a <code>Form</code> running on <code>thread1</code>, and from that I'm starting another thread (<code>thread2</code>). </p></li> <li><p>While <code>thread2</code> is processing some files I would like to update a <code>Label</code> on the <code>Form</code> with the current status of <code>thread2</code>'s work.</p></li> </ul> <p>How could I do that?</p> https://stackoverflow.com/q/301371 1489 Why is Dictionary preferred over Hashtable in C#? Nakul Chaudhary https://stackoverflow.com/users/34588 2008-11-19T09:24:24Z 2021-06-02T12:47:51Z <p>In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?</p> https://stackoverflow.com/q/372865 1358 Path.Combine for URLs? Brian MacKay https://stackoverflow.com/users/16082 2008-12-16T21:42:26Z 2021-08-31T11:44:55Z <p><a href="https://msdn.microsoft.com/en-us/library/system.io.path.combine%28v=vs.110%29.aspx" rel="noreferrer">Path.Combine</a> is handy, but is there a similar function in the .NET framework for <a href="http://en.wikipedia.org/wiki/Uniform_resource_locator" rel="noreferrer">URLs</a>?</p> <p>I'm looking for syntax like this:</p> <pre><code>Url.Combine("http://MyUrl.com/", "/Images/Image.jpg") </code></pre> <p>which would return:</p> <p><code>"http://MyUrl.com/Images/Image.jpg"</code></p> https://stackoverflow.com/q/4015324 1312 How to make an HTTP POST web request Hooch https://stackoverflow.com/users/465408 2010-10-25T14:05:58Z 2021-07-19T04:30:12Z <blockquote> <p><em>Canonical</em> <br> <strong>How can I make an HTTP request and send some data using the</strong> <code>POST</code> <strong>method?</strong></p> </blockquote> <p>I can do a <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer"><code>GET</code></a> request, but I have no idea of how to make a <a href="https://en.wikipedia.org/wiki/POST_%28HTTP%29" rel="noreferrer"><code>POST</code></a> request.</p> https://stackoverflow.com/q/14455293 1232 How and when to use ‘async’ and ‘await’ Dan Dinu https://stackoverflow.com/users/716092 2013-01-22T09:29:58Z 2021-09-28T04:14:41Z <p>From my understanding one of the main things that <a href="https://docs.microsoft.com/en-us/dotnet/csharp/async" rel="noreferrer"><code>async</code> and <code>await</code></a> do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic?</p> <p>I'm currently trying out the most basic example. I've added some comments inline. Can you clarify it for me?</p> <pre><code>// I don't understand why this method must be marked as `async`. private async void button1_Click(object sender, EventArgs e) { Task&lt;int&gt; access = DoSomethingAsync(); // task independent stuff here // this line is reached after the 5 seconds sleep from // DoSomethingAsync() method. Shouldn't it be reached immediately? int a = 1; // from my understanding the waiting should be done here. int x = await access; } async Task&lt;int&gt; DoSomethingAsync() { // is this executed on a background thread? System.Threading.Thread.Sleep(5000); return 1; } </code></pre> https://stackoverflow.com/q/232535 1173 How do I use reflection to call a generic method? Bevan https://stackoverflow.com/users/30280 2008-10-24T05:17:35Z 2021-08-09T14:35:29Z <p>What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?</p> <p>Consider the following sample code - inside the <code>Example()</code> method, what's the most concise way to invoke <code>GenericMethod&lt;T&gt;()</code> using the <code>Type</code> stored in the <code>myType</code> variable?</p> <pre><code>public class Sample { public void Example(string typeName) { Type myType = FindType(typeName); // What goes here to call GenericMethod&lt;T&gt;()? GenericMethod&lt;myType&gt;(); // This doesn't work // What changes to call StaticMethod&lt;T&gt;()? Sample.StaticMethod&lt;myType&gt;(); // This also doesn't work } public void GenericMethod&lt;T&gt;() { // ... } public static void StaticMethod&lt;T&gt;() { //... } } </code></pre> https://stackoverflow.com/q/1759352 1136 How to mark a method as obsolete or deprecated? Chris Ballance https://stackoverflow.com/users/1551 2009-11-18T21:53:38Z 2021-07-14T02:50:08Z <p>How do I mark a method as obsolete or deprecated using C#?</p> https://stackoverflow.com/q/1344221 1127 How can I generate random alphanumeric strings? KingNestor https://stackoverflow.com/users/64878 2009-08-27T23:07:24Z 2021-09-13T22:53:59Z <p>How can I generate a random 8 character alphanumeric string in C#?</p> https://stackoverflow.com/q/6201529 1091 How do I turn a C# object into a JSON string in .NET? Hui https://stackoverflow.com/users/763370 2011-06-01T12:59:21Z 2021-09-27T16:47:14Z <p>I have classes like these:</p> <pre><code>class MyDate { int year, month, day; } class Lad { string firstName; string lastName; MyDate dateOfBirth; } </code></pre> <p>And I would like to turn a <code>Lad</code> object into a <strong>JSON</strong> string like this:</p> <pre><code>{ &quot;firstName&quot;:&quot;Markoff&quot;, &quot;lastName&quot;:&quot;Chaney&quot;, &quot;dateOfBirth&quot;: { &quot;year&quot;:&quot;1901&quot;, &quot;month&quot;:&quot;4&quot;, &quot;day&quot;:&quot;30&quot; } } </code></pre> <p>(Without the formatting). I found <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx" rel="noreferrer">this link</a>, but it uses a namespace that's not in <strong>.NET 4</strong>. I also heard about <a href="http://james.newtonking.com/projects/json-net.aspx" rel="noreferrer">JSON.NET</a>, but their site seems to be down at the moment, and I'm not keen on using external DLL files.</p> <p>Are there other options besides manually creating a <strong>JSON</strong> string writer?</p> https://stackoverflow.com/q/10855 1086 LINQ query on a DataTable Calanus https://stackoverflow.com/users/445 2008-08-14T10:08:27Z 2021-09-22T18:38:30Z <p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p> <pre><code>var results = from myRow in myDataTable where results.Field("RowNo") == 1 select results; </code></pre> <p>This is not allowed. How do I get something like this working?</p> <p>I'm amazed that LINQ queries are not allowed on DataTables!</p> https://stackoverflow.com/q/847066 1080 Group By Multiple Columns Sreedhar https://stackoverflow.com/users/85952 2009-05-11T07:24:39Z 2021-05-07T00:32:12Z <p>How can I do GroupBy multiple columns in LINQ</p> <p>Something similar to this in SQL:</p> <pre><code>SELECT * FROM &lt;TableName&gt; GROUP BY &lt;Column1&gt;,&lt;Column2&gt; </code></pre> <p>How can I convert this to LINQ:</p> <pre><code>QuantityBreakdown ( MaterialID int, ProductID int, Quantity float ) INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity) SELECT MaterialID, ProductID, SUM(Quantity) FROM @Transactions GROUP BY MaterialID, ProductID </code></pre>