Convert DataTable to Array C# - c#

I have the following DataTable
ItemNumber Quantity Order
1 2 3
4 3 8
7 7 9
I would like to load first two columns into 2 dimensional array. If it is not possible, at least I would like to get first column into 1 dimension array.
Of course, I can write a loop, but I wonder if it is possible to avoid loops.
Regards,

You won't necessarily be able to avoid loops in the technical sense, but you could write something like this:
DataTable table = ...;
return table.Rows.Cast<DataRow>().Select(c => new[] { c[0], c[1] });
That's an array of arrays, rather than a multidimensional array. But from what I've seen multidimensional arrays seem to be phased out as standard practice in most applications. You might also want to parse each row in that Select to being some actual type.
If you leave this as an IEnumerable<>, it will not need to loop more than the once that you use it, but if you're reading at random points a lot (using the indexer, or what have you), you might want to append .ToArray(). That decision depends on how you're using it. As a general rule, it's nice to write code that doesn't depend on random access like that, since then you don't have to read from the DataTable more than once per record.

Related

How to use SkipWhile() to skip duplicate elements in two arrays?

I am trying to get a list of numbers (upto 9) that don't contain any numbers already in a 3x3 cell from which is contained within a 81 large 2d array of integers. I'm attempting to make sudoku. There are likely better solutions that have nothing to with skipwhile or something similar, but they all seem to rely on duplicate numbers having the same index in both array which doesn't work.
int[] inCellNumbers = thisCell.Intersect(Numbers).ToArray();
int[] availableNumbers = Numbers.SkipWhile(Numbers.Contains<int>(inCellNumbers) == true);
This is the code that I tried, numbers is an array of integers and I get this error:
'MemoryExtensions.Contains(ReadOnlySpan, int)' requires a receiver of type 'ReadOnlySpan'
I was attempting to skip all numbers that are in 'inCellNumbers' and have them in 'availableNumbers' from 'Numbers'
You can use the Enumerable.Except Method:
int[] availableNumbers = Numbers.Except(inCellNumbers).ToArray();
The Enumerable.SkipWhile Method stops skipping at the first element that does not fulfill the condition. Even if others follow later that do fulfill it.
I'm not sure of the algorithm for checking around a sudoku grid but it sounds like you would want to use some hashsets.
A hashset may only have unique entries. An array or list can be dumped to a hashset using its constructor new HashSet(arrOrList), and you can evaluate immediately to one from LINQ using .ToHashSet().
As for the error, it looks like you are using List<T>.Contains<T>(T item) (notice all of the T here), which is going to check if the List contains the entire parameterized array as a single element/item. Unless Numbers is of type List<int[]> this is going to be a problem, but I'm unsure of what type you give it so this may not be the true issue. I see you are using .Contains<int> but this won't work as inCellNumbers is int[]

Questions about Array and List in c# [duplicate]

This question already has answers here:
Array versus List<T>: When to use which?
(16 answers)
Closed 9 years ago.
I am not asking about the difference between array and list in general, I'm just asking about the difference between them in this scenario.
I have one Array. The array index is a dynamic value, and I have one integer List.
int DynamicValue=20 ;//It's any values should be coming from database or anywhere
int[DynamicValue] array1=new int[DynamicValue];//Array declaration
List<int> list1=New List<int>();//List declaration
Now I create one for loop to add values to Array and List:
//First add values in array
for(i=0;i<DynamicValue;i++)
{
array1[i]=i;
}
//Then add the values to list
for(i=0;i<DynamicValue;i++)
{
list1.Add(i);
}
Now what is this difference between the above codes ?
My questions are:
Array is type safe and also defined the index size. So why do many peoples like Lists in this scenario? (I know it's useful for generics coding, but I'm asking for this scenario)
The array for loop is not accruing any boxing and unboxing, So why would we need List?
Which for loop (Array or List) is best in this scenario ?
Which for loop will give good performance (I think both of for loops are good, because this code does not attempt any boxing and unboxing and also this codes is type safe. But I'm not sure at this time which one is better) ?
When you create an array you specify the size. When you create your list you do not (you can provide an initial capacity with an overload of the constructor).
So when you create the array you say it needs memory for the size of 20 int objects. But when you create the List it has no size reserved for the ints.
List<int> list = new List<int>();
Console.WriteLine(list.Capacity);
//Output: 0
Then when you use the loop to add items to the array the size of the array remains 20. But when you use the loop for the list the list sees there is no room. So it creates room for 4 items (check list.Capacity after first add). Then when the capacity is full the list will double its capacity. Now it is 8. Then again 16, then again 32. So in the end your list reserved room in memory for 32 int objects.
The array only reserved 20 so in total the array is better memory wise.
Further more, performance wise, array is also a little faster. I refer to this SO answer: https://stackoverflow.com/a/454923/637425
To adress some of your questions:
Many people don't like to work with indexes. You can make mistakes very easily (especially for starting programmers). Indexes are zero based etc etc... But if you could just call .Add() you don't have to worry about index. So it is a bit of convenience for most people to use List
You don't need list... See answer 1.
See my large story... Array is a bit better memory wise.
Both give good performance and you wont notice any difference. When you start using larger lists/arrays then it becomes interesting. For something with the size of 20 there is just not much performance gain.

any dynamic length two dimension structure in C#?

Please guide me, are there any out of box data structures in C# that support dynamic length and two or more dimensions?
I tried to use a string array but length is an issue. I want some structure that can be built and support 2 dimensions, like some text and its value.
Please suggest solutions.
How about a List<List<T>>?
First of all, "two or more dimensions" isn't all that specific.
Do you need 2? Or 3? Or more? What is "more" anyway?
Also, do you need a rectangular data set like a 2 dimensional array? Or do you need one that has different widths for different rows?
Also, your "some text and its value" suggests you're not really looking at a 2 dimensional data structure, but a 1 dimensional data structure, containing elements that have multiple values.
The difference here is that a 2 dimensional data structure would have the same type of elements in both dimensions, whereas the other can have different types of elements, like an int and a string.
So perhaps you need to tell us a bit more about what you need to store in that structure.
Otherwise, List<List<T>> it is.
If you want key-value pairs you can use a Hashtable or NameValueCollection.
It's not clear what you're asking. There are many ways to use the generic collections to build 2-dimensional data structures. What is it that you really want?
If you're talking about text data that you want to split into lines, and those lines can be modified, then how about List<StringBuilder>? That will allow you to add and delete lines, and you can also modify the individual lines.

How to get surrounding information from a cell in a table

Background
I'm looking for hints / pointers on how to approach this. When I search for table or grid, I get the UI stuff which is not what I'm looking for.
I don't know if this sounds like homework, but it is not. This is for a map of crops and I need to determine the crops planted around a particular plot of land.
Problem
I have a table of information, its 6 rows by 6 columns, but it can be any size.
I need to find a box in that table, and then get the information from all of the boxes around it.
|-1-|-2-|-3-|-4-|-5-|-6-|
|-7-|-8-|-9-|-A-|-B-|-C-|
|-D-|-E-|-F-|-G-|-H-|-I-|
|-J-|-K-|-L-|-M-|-N-|-O-|
|-P-|-Q-|-R-|-S-|-T-|-U-|
|-V-|-W-|-X-|-Y-|-Z-|-0-|
So I need to be able to pick box M and get the information for F,G,H,N,T,S,R,L
Note, if box J was needed, it is okay to return blanks or nulls for the boxes on the left that doen't exist. It does not wrap around and get the boxes from the other side of the table.
My Idea
I guess I could start with an array of arrays.
private static string[][] tableData;
So when looking for box M, I would need to get the row (i) and column (j) index for M, then the surrounding cells are as "simple" as:
| i-1, j-1 | i-1, j | i-1, j+1 |
| i, j-1 | i, j | i, j+1 |
| i+1, j-1 | i+1, j | i+1, j+1 |
And when asked for box M, I could find box M's index, then get the prior "row" and then index -1, index, and index + 1. Do that for M's row -1, M's row and then M's row + 1.
Is that a fair and good way of doing this or are there better, perhaps already built classes that I should use?
So the question: is an array of arrays the best way to handle this problem, or is there a better way?
There is nothing built in that will simply let you get "surrounding" cells in the way you describe.
A two dimensional char (or string) array looks like a good match, as you have already posted.
You can write wrap this in a class that can return a 3*3 array containing the neighbors.
The data structure that you choose is going to depend highly on the exact problem characteristics. For example, if you only have data in a small fraction of the cells and you have a lot of cells (tens of thousands or millions), you would probably want to implement a sparse array. Otherwise you can use a multi-dimensional array or jagged array.
Jagged array (the one that you mentioned):
private static string[][] tableData;
Multi-dimensional array:
private static string[,] tableData;
If you're not dealing with square plots, you might consider a completely different data structure altogether.
As well although multi-dimensional arrays may be easier to work with, jagged arrays have better performance on the CLR.
Why are multi-dimensional arrays in .NET slower than normal arrays?
Your array manipulation algorithms might drive you to choose one data structure over another too. All this said, I would recommend encapsulating your data structure inside a class so that you can more easily switch representations if needed.
(And I wouldn't use a DataTable. That's a whole lot of overhead for features that you're not using.)
C# has:
private static string[,] tableData;
Otherwise I think you approach is the correct one. Make sure you remember to consider the edges of the table though.

What is the fast way of getting an index of an element in an array? [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
I was asked this question in an interview. Although the interview was for dot net position, he asked me this question in context to java, because I had mentioned java also in my resume.
How to find the index of an element having value X in an array ?
I said iterating from the first element till last and checking whether the value is X would give the result. He asked about a method involving less number of iterations, I said using binary search but that is only possible for sorted array. I tried saying using IndexOf function in the Array class. But nothing from my side answered that question.
Is there any fast way of getting the index of an element having value X in an array ?
As long as there is no knowledge about the array (is it sorted? ascending or descending? etc etc), there is no way of finding an element without inspecting each one.
Also, that is exactly what indexOf does (when using lists).
How to find the index of an element having value X in an array ?
This would be fast:
int getXIndex(int x){
myArray[0] = x;
return 0;
}
A practical way of finding it faster is by parallel processing.
Just divide the array in N parts and assign every part to a thread that iterates through the elements of its part until value is found. N should preferably be the processor's number of cores.
If a binary search isn't possible (beacuse the array isn't sorted) and you don't have some kind of advanced search index, the only way I could think of that isn't O(n) is if the item's position in the array is a function of the item itself (like, if the array is [10, 20, 30, 40], the position of an element n is (n / 10) - 1).
Maybe he wants to test your knowledge about Java.
There is Utility Class called Arrays, this class contains various methods for manipulating arrays (such as sorting and searching)
http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html
In 2 lines you can have a O(n * log n) result:
Arrays.sort(list); //O(n * log n)
Arrays.binarySearch(list, 88)); //O(log n)
Puneet - in .net its:
string[] testArray = {"fred", "bill"};
var indexOffset = Array.IndexOf(testArray, "fred");
[edit] - having read the question properly now, :) an alternative in linq would be:
string[] testArray = { "cat", "dog", "banana", "orange" };
int firstItem = testArray.Select((item, index) => new
{
ItemName = item,
Position = index
}).Where(i => i.ItemName == "banana")
.First()
.Position;
this of course would find the FIRST occurence of the string. subsequent duplicates would require additional logic. but then so would a looped approach.
jim
It's a question about data structures and algorithms (altough a very simple data structure). It goes beyond the language you are using.
If the array is ordered you can get O(log n) using binary search and a modified version of it for border cases (not using always (a+b)/2 as the pivot point, but it's a pretty sophisticated quirk).
If the array is not ordered then... good luck.
He can be asking you about what methods you have in order to find an item in Java. But anyway they're not faster. They can be olny simpler to use (than a for-each - compare - return).
There's another solution that's creating an auxiliary structure to do a faster search (like a hashmap) but, OF COURSE, it's more expensive to create it and use it once than to do a simple linear search.
Take a perfectly unsorted array, just a list of numbers in memory. All the machine can do is look at individual numbers in memory, and check if they are the right number. This is the "password cracker problem". There is no faster way than to search from the beginning until the correct value is hit.
Are you sure about the question? I have got a questions somewhat similar to your question.
Given a sorted array, there is one element "x" whose value is same as its index find the index of that element.
For example:
//0,1,2,3,4,5,6,7,8,9, 10
int a[10]={1,3,5,5,6,6,6,8,9,10,11};
at index 6 that value and index are same.
for this array a, answer should be 6.
This is not an answer, in case there was something missed in the original question this would clarify that.
If the only information you have is the fact that it's an unsorted array, with no reletionship between the index and value, and with no auxiliary data structures, then you have to potentially examine every element to see if it holds the information you want.
However, interviews are meant to separate the wheat from the chaff so it's important to realise that they want to see how you approach problems. Hence the idea is to ask questions to see if any more information is (or could be made) available, information that can make your search more efficient.
Questions like:
1/ Does the data change very often?
If not, then you can use an extra data structure.
For example, maintain a dirty flag which is initially true. When you want to find an item and it's true, build that extra structure (sorted array, tree, hash or whatever) which will greatly speed up searches, then set the dirty flag to false, then use that structure to find the item.
If you want to find an item and the dirty flag is false, just use the structure, no need to rebuild it.
Of course, any changes to the data should set the dirty flag to true so that the next search rebuilds the structure.
This will greatly speed up (through amortisation) queries for data that's read far more often than written.
In other words, the first search after a change will be relatively slow but subsequent searches can be much faster.
You'll probably want to wrap the array inside a class so that you can control the dirty flag correctly.
2/ Are we allowed to use a different data structure than a raw array?
This will be similar to the first point given above. If we modify the data structure from an array into an arbitrary class containing the array, you can still get all the advantages such as quick random access to each element.
But we gain the ability to update extra information within the data structure whenever the data changes.
So, rather than using a dirty flag and doing a large update on the next search, we can make small changes to the extra information whenever the array is changed.
This gets rid of the slow response of the first search after a change by amortising the cost across all changes (each change having a small cost).
3. How many items will typically be in the list?
This is actually more important than most people realise.
All talk of optimisation tends to be useless unless your data sets are relatively large and performance is actually important.
For example, if you have a 100-item array, it's quite acceptable to use even the brain-dead bubble sort since the difference in timings between that and the fastest sort you can find tend to be irrelevant (unless you need to do it thousands of times per second of course).
For this case, finding the first index for a given value, it's probably perfectly acceptable to do a sequential search as long as your array stays under a certain size.
The bottom line is that you're there to prove your worth, and the interviewer is (usually) there to guide you. Unless they're sadistic, they're quite happy for you to ask them questions to try an narrow down the scope of the problem.
Ask the questions (as you have for the possibility the data may be sorted. They should be impressed with your approach even if you can't come up with a solution.
In fact (and I've done this in the past), they may reject all your possibile approaches (no, it's not sorted, no, no other data structures are allowed, and so on) just to see how far you get.
And maybe, just maybe, like the Kobayashi Maru, it may not be about winning, it may be how you deal with failure :-)

Categories