LINQ Interview Questions and Answers

<span class="Apple-style-span" style="font-family: Arial; font-size: 13px; white-space: pre; -webkit-border-horizontalspacing: 2px; -webkit-border-vertical-spacing: 2px; ">What is Language Integrated Query (LINQ)?

Answer :: Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:

Tools to create classes (usually called entities) mapped to database tables Compatibility with LINQ&rsquo;s standard query operations The DataContext class, with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more .... Read More
What are the main difference between LINQ and Stored Procedures?

Answer :: There are couple of advantage of LINQ over stored procedures. 1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries. 2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy. 3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception! .... Read More

<div class="post-text"> What are the pros and cons of LINQ (Language-Integrated Query)? What are the best and worst cases in which to use LINQ? How have you benefitted or not benefitted from using LINQ? Which data sources benefit the least and the most from LINQ?

Answer :: Pros: Declarative approach makes queries easier to understand and more compact Extensibility and expression trees allow mostly consistent querying of multiple sources Even in-process queries can be implemented in ways other than LINQ to Objects - e.g. Parallel LINQ and my own Push LINQ framework. Very flexible. Fabulously useful for in-process queries, where it's easiest to understand

Great to be able to avoid SQL in strings etc Wide range of operators provided by default, and others can easily be added for LINQ to Objects Language features introduced primarily for LINQ are widely applicable elsewhere (yay for lambdas) Cons: Query expressions aren't understood well enough, and are overused. Often simple method invocation is shorter and simpler. Inevitable inconsistencies between provider - impedance mismatch is still present, which is reasonable but needs to be understood There will always be some things you can do in SQL but not in LINQ Without understanding what's going on, it's easy to write very inefficient code It's hard to write a LINQ provider. This may well be inevitable, but more guidance from Microsoft would be appreciated. It's a new way of thinking about data access for most developers, and will need time for understanding to percolate Not specifically LINQ but related to it - the way extension methods are discovered in C# isn't granular enough Some operators are "missing", particularly the equivalents of <code>OrderBy</code> for things other than ordering - e.g. finding the item with the maximum value of a property Deferred execution and streaming are poorly understood (but improving) Debugging can be very tricky due to deferred execution and streaming I find it's best when dealing with in-process queries. They're easy to predict, understand and extend. Complementary technologies like LINQ to XML and Parallel LINQ are great. LINQ to Objects can be used almost anywhere. LINQ to SQL etc are really nice where they're appropriate, but they're harder to understand and need more expertise. They're also only applicable in certain areas of your code. .... Read More
Can you tell me about the disadvantages of LINQ over Stored Procedures?

Answer :: Network traffic: sprocs need only serialize sproc-name and argument data over the wire while LINQ sends the entire query. This can get really bad if the queries are very complex. However, LINQ's abstraction allows Microsoft to improve this over time. Less flexible: Sprocs can take full advantage of a database's featureset. LINQ tends to be more generic in it's support. This is common in any kind of language abstraction (e.g. C# vs assembler). Recompiling: If you need to make changes to the way you do data access, you need to recompile, version, and redeploy your assembly. Sprocs can sometimes allow a DBA to tune the data access routine without a need to redeploy anything. .... Read More
Can you tell me some advantages of LINQ over Stored Procedures?

Answer :: For basic data retrieval I would be going for Linq without hesitation.

namespace PhoneStore { static class Utils { static double CalculateSalesTax(double x) { x = x * 1..Generic.". Compile time safety when your schema changes is priceless. using System. return y. Objects and any other datasource without having to learn a new syntax . . using System." and not "return x. Because Linq can support querying anything that implements the IQueryable interface..<div class="post-text"> Since moving to Linq I've found the following advantages: Debugging my DAL has never been easier.Utils' I don't understand what this means or how to correct it. } } } when i compile I get the following error error CS0723: Cannot declare a variable of static type 'PhoneStore.0625.Collections. you will be able to use the same syntax to query XML.Text. Deployment is easier because everything is compiled into DLL's. any help would be great thanks Answer :: Don't know exactly how to fix it but in CalculateSalesTax should it really be "return y.Linq.. Read More I have the following code using System. using System. No more managing deployment scripts.

ado. asp.Linq.Windows.Forms. linq and their differences. jdbc . } .] point = new bool[51. using . 2:down.m in doubt to choose which one from . i need perfect definition about j2se java.ComponentModel. public Form1() { InitializeComponent().net . j2ee. . it is very similar to C++. using System. jsp.Perhaps that is the cause because it things it needs to create y? .. would u help me in this dilemma? i realy need this.thank u. Read More i. } private void InitializeComponent() { throw new NotImplementedException(). using System. using System.. c#. //sets the direction that the snake is supposed to move: 1:up. Read More trying to call paint method here is the code I have so far using System. 3:left. int direction = only works on Microsoft machines.Text. Plus. 51]. 4:right. using System.Drawing. //This sets the starting snake point[0.. using System. 0] = true. Java is platform independent. Answer :: You should use Java. using System... j2me. by the way i can program by c++ and vb. public partial class Form1 : Form { public class Snake { static void Main() { } } //somewhat of a coordinate system for the game bool[.

10). EventArgs e) { try { int x = 0. if (point[x. point[x . } } } private void timer1(object sender. y] = false. y] == true) { point[x.EventHandler(this. } } if (direction == 1) { if (point[x. y] == true) { point[x. } .1. point[x. y + 1] = true.= 50) { x = 0. y] == true) { point[x. private void Form1_Load(object sender. break. } } if (direction == 3) { if (point[x. while (y &lt. point[x + 1. y] = false. y++. break. y++. } if (x &lt.Form1_Load). } } if (x &gt. y] == true) { g.1] = true. } } Invalidate(). int y = 0. 10. y] = true. point[x. } if (x &lt. while (y &lt. PaintEventArgs e) { //according to the array point this displays the blocks of the snake and fruit Graphics g = e. skip = true. y] = false. x * 10. y .= 50) { x = 0. 51) { bool skip = false. 50 skip == false) { x++.//This method is necessary because InitializeComponent() calls it //this. if (direction == 4) { if (point[x. EventArgs e) { } private void Form1_Paint(object sender. y] = true. break. 51) { bool skip = false. y] == true) { point[x. skip = true.Load += new System. y] = false.Graphics. 50 skip == false) { x++. } } if (direction == 2) { if (point[x. y * 10. int y = 0.FillRectangle(Brushes. } if (x &gt.GreenYellow. int x = 0. break.

That way it's automatically called when the paint event is fired. // Do your drawing here. break. break. case "Down": direction = 2. case "Right": direction = 4. base. KeyEventArgs e) { // Invalidate the Eater before moving it string result = e. } Attaching to the event: Put this in your initializer: . } } } Answer :: You don't really call paint.KeyData.OnPaint(e). put this in your snake class: protected override void OnPaint(PaintEventArgs e) { // Call the base OnPaint event to make sure the rest of the form gets drawn. you can either overload it or attach to it.ToString(). switch (result) { case "Left": direction = 3. } } private void Form1_KeyDown(object sender. Overloading. break. case "Up": direction = 1.catch { MessageBox. break.Show("Game Over").

. } Hope this helps.Identity. I am too far into the development cycle. Answer :: You can simply store the retrieved value in a Session variable and read from the Session variable.Identity. Is there a way that I can do a single SQL call when they log on (in code-behind) that would reset the User.Data..this. PaintEventArgs e) { // Put your drawing code here } .PaintEventHandler ( YourFunction_Paint ). using System. Then add your function that does the drawing to the form: private void YourFunction_Paint(object sender.Drawing.Text. I am using MS SQL and I don't want to mess with LINQ. using System. Read More I am using the User.Name to the proper caps (as entered in my db)? I just need a code sample or something.... //later when you want to retrieve the value you can use: string UserName.Windows. using System. using System.Drawing.Windows.Paint += new System. . the problem is that User. if(Session["UserName"] != null) { UserName = Session["UserName"]. but that is processor overhead that I don't want.Linq.Name.Forms. namespace WindowsFormsApplication1 { public partial class Form1 : Form .Identity. Read More using System. using System..Collections.Name property to display my users name when they comment on things on my site. using System.Forms. First time you read the username (when a user logs in): Session["UserName"] = User.ComponentModel. so their names are hardly ever capitalized as they should be.ToString(). Now I had been using an SQL call to access their proper names.Generic. using System.Identity.Name works using data they entered at Login.Drawing2D. using System.

Read More I have this code completed so far but i cannot get anything to pop up when i build solution.. namespace Snakin { public partial class Form1 : Form { //somewhat of a coordinate system for the game ..CreateGraphics() (from whatever function).cs using System.15 . PaintEventArgs e) { Graphics g = e. Rectangle sun = new Rectangle(Width-100. grass).FillRectangle(grn. Answer :: A simple way would be to break paint out into its own function (with a graphics object as a parameter) then call it with either e. Height). Brush grn = new SolidBrush(Color. Height).SkyBlue).Forms. Brush blu = new SolidBrush(Color. using System. Rectangle grass = new Rectangle(0. Width.. 300. using System.ComponentModel. sun). sky).FillRectangle(blu. 80). g..Generic.FillEllipse(yel.Windows.Yellow). g. using System.Collections. Brush yel = new SolidBrush(Color. Rectangle sky = new Rectangle(0. using System. . Form1. 0. I will include the code and if anyone can help me to get output I would greatly appreciate it.Green). 80. using System. g.Text.{ public Form1() { InitializeComponent()..Data. using System.Graphics.. Width.Graphics (from onPaint) or with Form1.Drawing.. } private void onPaint(object sender.

skip = true. x * 10. y * 10.= 50) { x = 0. break. break. 50 skip == false) { x++. } if (x &lt. 10. 0] = true. if (point[x. int x = 0. } } } private void Form1_KeyDown(object sender. case "Right": direction = 4. while (y &lt. break. int y = 0.] point = new bool[51. PaintEventArgs e) { //according to the array point this displays the blocks of the snake and fruit Graphics g = e. int direction = 4. switch (result) { case "Left": direction = 3. y++. y] == true) { g.ToString(). } private void Form1_Paint(object sender.KeyData. //sets the direction that the snake is supposed to move: 1:up. 51].GreenYellow. case "Up": direction = 1. } } . 51) { bool skip = false. //This sets the starting snake point[0. 10). 4:right. case "Down": direction = 2.Graphics. } if (x &gt. break. 2:down. 3:left.bool[. public Form1() { InitializeComponent().FillRectangle(Brushes. KeyEventArgs e) { // Invalidate the Eater before moving it string result = e.

y] = false. y] == true) { point[x. while (y &lt. } if (x &lt. point[x. point[x + 1. y . y] = false. int y = 0.cs using System. y] = false. } } if (direction == 3) { if (point[x.Forms. } } Invalidate(). using System. using System. break.Linq. y] = true. if (direction == 4) { if (point[x. break. } catch { MessageBox.private void timer1_Tick_1(object sender. y] = true. skip = true. y++. } } } } Program.Windows.1. point[x .Collections.= 50) { x = 0. namespace Snakin { static class Program { /// &lt. } } if (x &gt. y] == true) { point[x. } } if (direction == 1) { if (point[x. y] = false.1] = true. /// The main entry point for the application.summary&gt. break.Generic. y] == true) { point[x. } } if (direction == 2) { if (point[x. 51) { bool skip = false. EventArgs e) { try { int x = 0. y + 1] = true. point[x. y] == true) { point[x. using System. 50 skip == false) { x++.Show("Game Over"). break. .

If that doesn't fix the problem I need to see your Form1. c.Linq. public mainWindow() { InitializeComponent().. Button b1.Text.Run(new Form1()). } } } Answer :: Try putting timer1.IO.Designer.. count = 0.Start() at the end of the Form1 constructor. blank. Application. EventArgs e) { AutoSize = true.ComponentModel. using System. using System.Collections...Generic.. [STAThread] static void Main() { Application. } private void Form1_Load(object sender./// &lt. namespace pipeworksSlidingPuzzle { public partial class mainWindow : Form { int rows. . using System.Data. String path = "F:\\IT312\\pipeworksSlidingPuzzle\\pipe. bool shuffling.cs.SetCompatibleTextRenderingDe. int index = 0. int tileWidth.Windows. using System.Drawing.. using System. ./summary&gt.EnableVisualStyles(). Read More using System. Application. cols. r..Forms. bool secondClick = false. using System. using System. tileHeight. using System.

Random rnd = new Random().Click += new EventHandler(ButtonClick). } shuffling = false. null). for (int i = 0.Location = new Point(c * 100. Controls. i++) { int x = rnd. b.1. } } blank = rows * cols . pb_Click(Controls[x]. count = 0.Location.Location = pb.1 c == cols . 100)..FixedSingle. r++) { for (int c = 0.BringToFront().Next(rows * cols .jpg"). b.Size.1) { break. if (count==2) { index++. "*. for (int r = 0.Size = new Size(100. pb.Margin = new Padding(0).FromFile(files[index]). pb. b.SizeMode = PictureBoxSizeMode. } Controls. shuffling = true. pb. rows.GetFiles(path. pb. Button b = new Button().BorderStyle = BorderStyle.1) + 1.Add(b). c++) { if (r == rows . r &lt.. . r * 100).Tag = pb. } private void Shuffle() { // shuffle.StretchImage. 1000. } PictureBox pb = new PictureBox(). c &lt.Tag = index. b. pb.Image = Image. i &lt. pb. b. cols.Size = pb. count++.String[] files = Directory. pb.Add(pb).

int trow = tileIndex / cols. } // up.Tag = tileIndex. tileHeight..Top++. // down. int tcol = tileIndex % rows.Top -= tileHeight.. } else { for (int i = 0. i &lt.Show("nalpas!!!").. int bcol = blank % rows. } void pb_Click(object sender. if (isSolved()) { . } else { for (int i = 0.Refresh(). tileIndex += cols. } } blank = tileIndex. } } blank = tileIndex. int tileIndex = (int) o. pb. } return. i++) { pb. if (tcol == bcol trow + 1 == brow) { if (shuffling) { pb. if (isSolved()) { MessageBox. pb.Tag.Tag = tileIndex. tileIndex -= cols. object o = pb. EventArgs e) { int brow = blank / cols.Top += tileHeight. i++) { pb. PictureBox pb = (PictureBox) sender. i &lt.Top--.1 == brow) { if (shuffling) { pb. if (tcol == bcol trow . tileHeight..

tileIndex++.Show("nalpas!!!"). tileIndex--. Read More Hello fellow programmers! I originally did a undergraduate in mathematics and the only 'coding' software development I did was in Matlab.Left--.Left -= tileWidth. Please check the syntax.. i++) { pb. } } blank = tileIndex.Show("nalpas!!!"). } // right. i &lt. pb.. pb. } else { for (int i = 0. I went out and worked for a number of years as a Quantative Analyst for a Financial Software Development Team and decided to go back to uni to learn Scientific . } else { for (int i = 0. and VBA (Excel) and to a smaller extent C .MessageBox.Left++..Left += tileWidth. } } blank = tileIndex. } // left..Tag = tileIndex.Tag = tileIndex. if (tcol + 1 == bcol trow == brow) { if (shuffling) { pb. if (isSolved()) { MessageBox. if (tcol . tileHeight. tileHeight. if (isSolved() Answer :: The syntax is wrong. i &lt.1 == bcol trow == brow) { if (shuffling) { pb. } return. i++) { pb..but purely from a procedural perspective. . } return...

.WriteLine("Enter n to display name and student number"). C# and Java are better. However. userIn = Console.Linq. for projects that include a lot of UI work. Even with all the JIT improvements. Console..WriteLine("Enter t to enter the times tables. Is C++ worth the extra work. Console. I have to admit on the surface Java and C# are appealing as they are so strongly typed. but I'm finding it really difficult choosing a language that I want to specialise in. For the form and database work. C# and Java are significantly better."). . Console. Fortran and Ada offer . however I really enjoy the flexibility and absolute control that C++.but in terms of the work involved in application development I have noticed a severe increase in the amount of time required.Text. using System. using System. .Collections.WriteLine("Enter e to exit").. while (userIn != "e") { Console.WriteLine("Please Select an Option"). the libraries are significantly larger.ReadLine(). namespace ConsoleApplication30 { class Program { static void Main(string[] args) { string userIn = "0". or am I better off sticking with Java and C# ? I plan on doing alot of Form application development involving LINQ and Access/SQL Server communication Any guidance would be greatly appreciated. Console. then C++ is very useful.WriteLine(). with large or long running data sets. C++ still runs faster and in less memory than Java or even C#. which I love.Generic. Read More using System. David Answer :: I think that if you are donig scientific work. using System.Software Development.

} } . else if (userIn == "t") TimeMeth().WriteLine ("Error {0} is Invalid".if (userIn == "n") NameMeth(). else if (userIn != "e") Console.userIn).

WriteLine("Please Enter an Integer"). Console. int y.ReadLine(). int total.ToInt32(userIn). x++) { total = y * x. Console. } public static void TimeMeth() { int x. x &lt. } } I want to ask the user for the interger in the if statement and then pass it off to the method name TimeMeth but i keep getting an error with the last else. How do I do this? . userIn = Console.public static void NameMeth() { Console. x.WriteLine("Name:Thomas Anderson \nStudent#: 300495656"). for (x = 1. total). string userIn = "0".WriteLine("{0} times {1} is {2}".= 12. y. y = Convert.

WriteLine(). Same with while (cond {}.Answer :: I think that the following does what you have in mind. Console. } else if (userIn == "t") { TimeMeth().WriteLine("Enter e to exit").begin namespace ConsoleApplication30 { class Program { static void Main(string[] args) { string userIn = "0".WriteLine("Please Select an Option"). Console. } . If you use the free Visual Studio Express 2008 from Microsoft. if (userIn == "n") { NameMeth()."). The same for "else if (cond)": use { and }. while (userIn != "e") { Console. you will see the matching parens or braces highlighted.WriteLine("Enter t to enter the times tables.ReadLine(). Always be careful with your curly braces { and }. If you write if (cond) always start with { and } after the condition. userIn = Console. Have fun with C#! //----------. Console. The code will also be indented properly to reflect the logic.WriteLine("Enter n to display name and student number"). Console.

total). string userIn = "0". x &lt. int total.WriteLine("Error {0} is Invalid". the program displays the name of the oldest. Read More I am trying to write a program that prompts 5 users to enter in their names and ages. .. x++) { total = y * x. please assist..WriteLine("Name:Thomas Anderson \nStudent#: 300495656").else if (userIn != "e") { Console. } } } } //----------------------. Console.. } public static void TimeMeth() { int x. y = Convert.. after the information has been entered.ReadLine(). } } } public static void NameMeth() { Console. but there has to be an easier way. the code is listed.= 12.. Console.. x. userIn = Console.WriteLine("{0} times {1} is {2}"..WriteLine("Please Enter an Integer"). y. for (x = 1.end . int y. I know I could use a method as well as a loop but I could not figure it out how to do it. userIn).ToInt32(userIn). the names and ages are then put into a set of arrays. I realize that I could use quite a bit of if then statements to get my program to display the oldest persons name.

Generic. namesjumble[1].ReadLine().WriteLine(""). using System. Console.ToInt32(agetxt[0]). .ReadLine(). namespace ConsoleApplication1 { class Program { public static void Main(string[] args) { int[] agenmber = new int[5]. agetxt[1]). what is your age?". using System.Linq. agetxt[0]). Console.WriteLine("the second person to enter a name is {0} with an age of {1} years".ReadLine(). string[] namesjumble = new string[5]. using System. // information for the third person Console. Console. namesjumble[1] = Console.WriteLine("Hello {0}. agenmber[0] = Convert.WriteLine("USER 1 INFORMATION"). //information on the first person Console.using System.WriteLine(""). agetxt[1] = Console. Console. namesjumble[0]).ReadLine(). Console. agenmber[1] = Convert. namesjumble[0].ToInt32(agetxt[1]).Text.WriteLine("USER 2 INFORMATION"). Console.WriteLine("").WriteLine(""). // information for the second person Console.WriteLine("Hello {0}. Console.WriteLine("USER 3 INFORMATION"). Console. what is your age?". agetxt[0] = Console.WriteLine("").Collections. namesjumble[0] = Console. namesjumble[1]).WriteLine("the first person to enter a name is {0} with an age of {1} years". Console.WriteLine("what is your name?"). Console.WriteLine("what is your name?"). Console. string[] agetxt = new string[5].

WriteLine("USER 5 INFORMATION"). agetxt[3] = Console. Console. agetxt[4]). Console.WriteLine(""). namesjumble[2] = Console.WriteLine("Hello {0}. } else if (agenmber[1] &gt. agenmber[2] agenmber[0] &gt. agenmber[1] agenmber[2] &gt. agenmber[0] agenmber[2] &gt.ToInt32(agetxt[3]). namesjumble[4].WriteLine("").WriteLine(""). agenmber[4]) { Console.WriteLine("what is your name?"). namesjumble[2]. namesjumble[2]). agenmber[4] = Convert.ReadLine(). namesjumble[0]). Console. Console. Console. Console. agenmber[1] agenmber[0] &gt. namesjumble[3] = Console.WriteLine("the fourth person to enter a name is {0} with an age of {1} years". namesjumble[4]). namesjumble[3]).ReadLine().ToInt32(agetxt[2]). agenmber[2] = Convert.WriteLine("Hello {0}.WriteLine("Hello {0}. agetxt[2] = Console.Console.WriteLine("what is your name?").ReadLine(). if (agenmber[0] &gt. agenmber[2] agenmber[1] &gt. Console. what is your age?". agenmber[3] = Convert.WriteLine("the third person to enter a name is {0} with an age of {1} years".WriteLine("the fifth person to enter a name is {0} with an age of {1} years". agenmber[3] agenmber[1] &gt. Console. agenmber[3] agenmber[0] &gt.ReadLine(). Console. namesjumble[4] = Console. } else if (agenmber[2] &gt. Console. what is your age?".WriteLine("what is your name?"). // information for the fifth person Console.ReadLine().ToInt32(agetxt[4]). agenmber[3] agenmber[2] &gt. what is your age?". Console. agenmber[4]) { . agenmber[0] agenmber[1] &gt. namesjumble[3]. agetxt[3]). Console. namesjumble[1]).WriteLine("{0} is the oldest".WriteLine("{0} is the oldest". // information for the fourth person Console. agenmber[4]) { Console. agetxt[4] = Console. agetxt[2]).WriteLine("USER 4 INFORMATION").WriteLine("").ReadLine().

} } After this loop your result will contain an index of the oldest user in the array. } Again use the loop to get your oldest user. } Console. if (age[counter] &gt. agenmber[1] agenmber[3] &gt.. } if (agenmber[4] &gt. agenmber[3] agenmber[4] &gt. output("Enter User {0} info.WriteLine("{0} is the oldest". agenmber[1] agenmber[4] &gt. } if (agenmber[3] &gt. loop (some condition){ incrCounter(). agenmber[2] agenmber[3] &gt. namesjumble[2])..WriteLine("{0} is the oldest".. loop (some condition){ incrCounter().. namesjumble[4]).. age[counter+1]){ result = counter. } Answer :: More common and generic approach would be to write prompts and read input inside the loop. agenmber[0]) { Console. Read More . agenmber[4]) { Console.. readYourInput().Console.ReadLine(). agenmber[0] agenmber[3] &gt.. namesjumble[3])..WriteLine("{0} is the oldest".."). . agenmber[2] agenmber[4] &gt..

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.