Top Questions on Stack Overflow

List of Tags


One of the things I've asked a lot about on this site is LINQ. The questions I've asked have been wide and varied and often don't have much context behind them. So in an attempt to consolidate the knowledge I've acquired on Linq I'm posting this question with a view to maintaining and updating it with additional information as I continue to learn about LINQ.

I also hope that it will prove to be a useful resource for other people wanting to learn about LINQ.

What is LINQ?

From MSDN:

The LINQ Project is a codename for a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

What this means is that LINQ provides a standard way to query a variety of datasources using a common syntax.

What flavours of LINQ are there?

Currently there are a few different LINQ providers provided by Microsoft:

There are quite a few others, many of which are listed here.

What are the benefits?

  • Standardized way to query multiple datasources
  • Compile time safety of queries
  • Optimized way to perform set based operations on in memory objects
  • Ability to debug queries

So what can I do with LINQ?

Chook provides a way to output CSV files
Jeff shows how to remove duplicates from an array
Bob gets a distinct ordered list from a datatable
Marxidad shows how to sort an array
Dana gets help implementing a Quick Sort Using Linq

Where to start?

A summary of links from GateKiller's question are below:
Scott Guthrie provides an intro to Linq on his blog
An overview of LINQ on MSDN

ChrisAnnODell suggests checking out:

What do I need to use LINQ?

Linq is currently available in VB.Net 9.0 and C# 3.0 so you'll need Visual Studio 2008 or greater to get the full benefits. (You could always write your code in notepad and compile using MSBuild)

There is also a tool called LinqBridge which will allow you to run Linq like queries in C# 2.0.

Tips and tricks using LINQ

This question has some tricky ways to use LINQ

Answered By: ChrisAnnODell ( 31)

Another good site for Linq is Hooked on Linq and here are 101 Linq samples which are a great reference if you just want a quick syntactical example.

Let's also not forget LinqPad :)

I know there is a standard behind all C compiler implementations, so there should be no hidden features. Despite that, I am sure all C developers have hidden/secret tricks they use all the time.

Answered By: tonylo ( 117)

More of a trick of the GCC compiler, but you can give branch indication hints to the compiler (common in the Linux kernel)

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)


What I like about this is that it also adds some expressiveness to some functions.

void foo(int arg)
     if (unlikely(arg == 0)) {

I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.

Answered By: Jason Bunting ( 186)

Simple enough:

for(var propertyName in myObject) {
   // propertyName is what you want
   // you can get the value like this: myObject[propertyName]

Now, you will not get private variables this way because they are not available.

EDIT: @bitwiseplatypus is correct that unless you use the hasOwnProperty() method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.

Now, that said, hasOwnProperty() is useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.

EDIT 2: @bitwiseplatypus brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use hasOwnProperty(). Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via jQuery.extend and jQuery.fn.extend).


For example, I would prefer to write my commit messages in vim, but it is opening emacs.

How do I configure git to always use vim instead? Note that I want to do this globally, not just for a single project.

Answered By: Mark Rushakoff ( 71)

From man git-commit:


The editor used to edit the commit log message will be chosen from the GIT_EDITOR environment variable, the core.editor configuration variable, the VISUAL environment variable, or the EDITOR environment variable (in that order).


PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array contains only numeric keys?

Basically, I want to be able to differentiate between this:

$sequentialArray = array('apple', 'orange', 'tomato', 'carrot');

and this:

$assocArray = array('fruit1' => 'apple', 
                    'fruit2' => 'orange', 
                    'veg1' => 'tomato', 
                    'veg2' => 'carrot');
Answered By: Greg ( 85)

This will do it for you

function isAssoc($arr)
    return array_keys($arr) !== range(0, count($arr) - 1);

var_dump(isAssoc(array('a', 'b', 'c'))); // false
var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))); // false
var_dump(isAssoc(array("1" => 'a', "0" => 'b', "2" => 'c'))); // true
var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))); // true


There are known issues with this function:

var_dump(isAssoc(array(1 => 'string'))); // Should return false, but returns true.

Look at the other answers, particularly this one, for alternatives.


I have followed the tutorial at Scala and Android with Scala 2.7.3 final. The resulting Android App works but even the most basic application takes several minutes (!) to compile and needs 900 kb compressed, which is a show stopper for mobile applications. Additionally, the IDE runs out of memory every now and then. I assume dex is not made for big libraries like the scala-library.

So my question is: Has anyone actually done this and is there any cure for this?

Answered By: Wade Mealing ( 79)

I've written some basic Android applications in Scala, nothing too epic. Not being a Java programmer I was suggested to use a "treeshake", I was explained by a friend that this strips out all the unnecessary libraries from the jar files.

I have not documented it, but I found that someone else already has:

Proguard is not the only solution, you might find something that suits your work flow or is more suited for your environment.


A while ago I came across some code that marked a member variable of a class with the mutable keyword. As far as I can see it simply allows you to modify a variable in a const method:

class Foo  
    mutable bool done_;  
    void doSomething() const { ...; done_ = true; }  

Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a boost::mutex as mutable allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.

Answered By: KeithB ( 91)

That is all there is to mutable. It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.


What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?

Let's say I have an object o. How do I check whether it's a str?

Answered By: Fredrik Johansson ( 193)

To check if the type of o is exactly str:

type(o) is str

To check if o is an instance of str or any subclass of str (this would be the "canonical" way):

isinstance(o, str)

The following also work, and can be useful in some cases:

issubclass(type(o), str)
type(o) in ([str] + str.__subclasses__())

See Built-in Functions in the Python Library Reference for relevant information.

One more note: in this case, you may actually want to use

isinstance(o, basestring)

because this will also catch Unicode strings (unicode is not a subclass of str; both str and unicode are subclasses of basestring).

Alternatively, isinstance accepts a tuple of classes. This will return True if x is an instance of any subclass of any of (str, unicode):

isinstance(o, (str, unicode))
Vicent Marti

Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?


void format_string(char *fmt, ...);

void debug_print(int dbg_lvl, char *fmt, ...) {
    format_string(fmt, /* how do I pass all the arguments from '...'? */);
    fprintf(stdout, fmt);
Answered By: Shane MacLaughlin ( 89)

To pass the ellipses on, you have to convert them to a va_list and use that va_list in your second function. Specifically;

void format_string(char *fmt,va_list argptr, char *formatted_string);

void debug_print(int dbg_lvl, char *fmt, ...) 
 char formatted_string[MAX_FMT_SIZE];

 va_list argptr;
 format_string(fmt, argptr, formatted_string);
 fprintf(stdout, "%s",formatted_string);

This answer has been edited to reflect concerns in the comment by Thomas Padron-McCarthy. See comments for further details.

Jon Tackabury

I see these 2 acronyms thrown around, and I was wondering if there are any differences between a GUID and a UUID?

Answered By: bdukes ( 172)

GUID is Microsoft's implementation of the UUID standard.

Per Wikipedia:

The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.