How can i programatically push an array of strings into generic Stack ?
string array
string[] array=new string[]{"Liza","Ana","Sandra","Diya"};
Stack Setup
public class stack<T>
{
private int index;
List<T> list;
public stack()
{
list = new List<T>();
index=-1;
}
public void Push(T obj)
{
list.Add(obj);
index++;
}
...........
}
What is the change do i need here ?
stack<string> slist = new stack<string>();
var v = from vals in array select (p => slist.Push(p));
Error Report :
The type of the expression in the select clause is incorrect.
LINQ is a query language/framework. What you want to perform here is a modification to a collection object rather than a query (selection) - this is certainly not what LINQ is designed for (or even capable of).
What you might like to do, however, is to define an extension method that for the Stack<T> class, however. Note that it also makes sense to here to use the BCL Stack<T> type, which is exactly what you need, instead of reinventing the wheel using List<T>.
public static void PushRange<T>(this Stack<T> source, IEnumerable<T> collection)
{
foreach (var item in collection)
source.Push(item);
}
Which would then allow you do the following:
myStack.PushRange(myCollection);
And if you're not already convinced, another philosophical reason: LINQ was created to bring functional paradigms to C#/.NET, and at the core of functional programming is side-effect free code. Combining LINQ with state-modifying code would thus be quite inconsistent.
The first issue is you Push returns a void. Select is expecting a value of something.
You are just doing a loop and don't need to use link.
Since you stack is internally storing a list, you can create a list by passing it an array.
so in your case
List<string> myList = new List<string>(array);
Creats the list.
Change
public void Push(T obj)
to
public T Push(T obj)
and ignore the return values.
Disclaimer: I would not recommend mutation like this.
Try this
string[] arr = new string[]{"a","f"};
var stack = new Stack<string>();
arr.ToList().ForEach(stack.Push);
While this is "cool" is isn't any better than a for loop.
Push needs a return type for you to be able to use it in a select clause. As it is, it returns void. Your example is, I think, a horrible abuse of LINQ. Even if it worked, you'd be using a side-effect of the function in the select clause to accomplish something totally unrelated to the task that the select is intended for. If there was a "ForEach" extension, then it would be reasonable to use LINQ here, but I'd avoid it and stick with a foreach loop.
foreach (var val in array)
{
slist.Push(val);
}
This is much clearer in intent and doesn't leave one scratching their head over what you're trying to accomplish.
Related
Is it, in general, better to do this:
public void Foo1(List<int> list)
{
list.Add(1);
}
or this:
public List<int> Foo2()
{
List<int> list = new List<int>();
list.Add(1);
return list;
}
The reason I ask is because I'm doing it the first way at the moment (except the method is different and more complicated obviously), which requires me to always use two lines to call the method as such (this adds up to a lot of extra lines):
List<int> list = new List<int>();
Foo1(list);
whereas with the second way I can just use one line:
List<int> list = Foo2();
So which way is better, with time and space in mind?
Edit: Okay so more specifically, I have a method that adds all the controls of type T from a ControlCollection to a List.
public static void GetControlsRec<T>(Control.ControlCollection controlCollection, List<T> resultCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
resultCollection.Add((T)control);
if (control.HasChildren)
GetControlsRec(control.Controls, resultCollection);
}
}
Which would be better in this case?
In general, I typically try to avoid changing/mutating an existing collection. As such, I'd almost always prefer your second option.
That being said, it does have the disadvantage of creating a new List<T>, which means more memory allocations. If (and only if) performance is an issue in that specific piece of code, you may want to consider modifying the input list directly, though I would suggest picking a method name which makes it obvious you're mutating the collection.
So the problem that you have is that you have a recursive method in which each call to the method conceptually adds some number of items to a result collection. This leads to two conceptual approaches, which you correctly identified:
Have each recursive call return a collection of all of the results that it represents. This requires each call to pull out the results of any recursive calls and add them to its own collection. This is rather inefficient and wasteful; you end up copying data around over and over again. (That is, unless you use a data structure that can efficiently "add all of the results from another instance of the same type". A LinkedList (that you rolled yourself, as the .NET version doesn't support this) could do this well, or some of the immutable data structures perhaps.)
Pass in a mutable collection type and have each recursive call mutate the collection. This will perform well, but leads to the problem that the code is hard to reason about. You can't just pull out one "sub tree" and look at that in isolation. It's also awkward for the caller in that they need to create a collection, leave it empty, store a reference to it so that they can access it after calling the method, etc. This is just very confusing and error prone.
option 1, as much as it makes things easier on the programmer, is really very wasteful (if you don't do some sort of optimization through the use of another type of collection, as described). If you do go with the section option I would strongly suggest abstracting that away from the caller. Specifically, make the overload accepting a List private, and have a separate public overload of the method without the extra parameter that passes in a list it creates to the private overload and then returns that list. This lets the caller think that you're using an approach similar to the the first method, while still getting the performance benefits of the second. It still does complicate development though.
The other option is to just avoid recursion entirely, which is my personal preference. When you solve the problem iteratively, not recursively, all of the problems just go away:
public static IEnumerable<Control> GetAllChildren(this Control root)
{
var stack = new Stack<Control>();
stack.Push(root);
while (stack.Any())
{
var next = stack.Pop();
foreach (Control child in next.Controls)
stack.Push(child);
yield return next;
}
}
(If you want all controls of a particular type simply call OfType on the result of this query, it's really best to separate out the logical operations of "get all of the children" from "filter the collection to just these types of controls".)
In your specific case, I would recommend a generator:
public static IEnumerable<T> GetControlsRec<T>(Control.ControlCollection controlCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
yield return (T)control;
if (control.HasChildren)
foreach (T descendant in GetControlsRec(control.Controls))
yield return descendant;
}
}
and then:
list.AddRange(GetControlsRec<…>(…));
(Sorry if the syntax isn’t quite right, but you get the idea.)
In the generic case, there is no one blanket answer IMHO. It really depends on the context and circumstances.
In this specific case, I would probably return an IEnumerable instead and let the caller decide to put it in a list or not:
public static IEnumerable<T> GetControlsRec<T>(Control.ControlCollection controlCollection)
where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
yield return (T)control;
if (control.HasChildren)
foreach (T child in GetControlsRec(control.Controls))
yield return child;
}
}
Or better yet, slap an extension method onto Control itself, something akin to:
public static IEnumerable<T> GetDecendentsOfType<T>(this Control c)
{
foreach (Control control in c.Controls)
{
if (control is T)
yield return (T)control;
if (control.HasChildren)
foreach (T child in control.GetDecendentsOfType<T>())
yield return child;
}
}
which could then simply be called like:
Control myControl = Master.MakeMeAControl();
List<CheckBox> allCheckBoxesInControl = myControl.GetDecendentsOfType<CheckBox>().ToList();
There is no [detectable] difference between
List<int> list = new List<int>();
Foo(list);
.
.
.
void Foo( List<int> c )
{
c.Add(1) ;
return ;
}
and
List<int> list = Foo();
.
.
.
List<int> Foo()
{
List<int> c = new List<int>() ;
c.Add(1) ;
return c;
}
The first does a little work not done by the second in passing the parameter on the call to Foo(); the second does a little work not done by the first in returning the List<int> from the call to Foo(). Outside of that, there's essentially no difference.
Figure out the syntax you want to use (and one that makes sense for your design) and use that. Almost always, clarity and maintainability trump anything else. It's exceedingly unlikely that something like this would have any impact on performance.
And even easier, you could simply get rid of Foo() altogether. Something like:
List<int> c = Enumerable.Range(1,1).ToList() ;
or
List<int> c = new List<int>( new int[]{1} ) ;
should do you.
Given your extra information I think the way you currently have it is correct. Since your using recursion to walk a tree you can keep passing down the list. If you didn't pass the list in then you'd have to create it (once for each level of recursion).
public static List<T> resultCollection GetControlsRec<T>(Control.ControlCollection controlCollection) where T : Control
{
///Create new collection
List<T> resultCollection = new List<T>();
foreach (Control control in controlCollection)
{
if (control is T)
resultCollection.Add((T)control);
if (control.HasChildren)
resultCollection.AddRange(GetControlsRec(control.Controls, resultCollection));
}
return resultCollection;
}
What I generally do is
public IList<int> Foo1(IList<int> list)
{
list.Add(1);
return list;
}
For me it's more readable because you identify clearly the input and the output.
And because objects are passed by reference the performance is the same.
Hope it helps ^^
In my project, I implemented a service class which has a function naming GetList() which is as follows:
IList<SUB_HEAD> GetList(string u)
{
var collection = (from s in context.DB.SUB_HEAD where (s.head_code.Equals(u))
select s);
return collection.ToList();
}
which can also be implemented as
Arraylist unitlist= new Arraylist();
ObjectSet<SUB_HEAD> List = subheadService.GetAll();
foreach(SUB_HEAD unit in List)
{
unitlist.Add(unit.sub_head_code);
}
Purpose of doing this is to populate dropdown menu.
My question is that "which of the above method will be more efficient with respect to processing?" because my project have lot of places where i have to use drop down menu.
Please, just use the LINQ version. You can perform optimizations later if you profile and determine this is too slow (by the way, it won't be). Also, you can use the functional-style LINQ to make a single expression that I think reads better.
IList<SUB_HEAD> GetList(string u)
{
return context.DB.SUB_HEAD.Where(s => s.head_code == u).ToList();
}
The ToList() method is going to do exactly the same thing as you're doing manually. The implementation in the .NET framework looks something like this:
public static class Enumerable
{
public static List<T> ToList<T>(this IEnumerable<T> source)
{
var list = new List<T>();
foreach (var item in source)
{
list.Add(item);
}
return list;
}
}
If you can express these 4 lines of code with the characters "ToList()" then you should do so. Code duplication is bad, even when it's for something this simple.
Is it possible to create an extension method to return a single property or field in a list of objects?
Currently I have a lot of functions like the following.
public static List<int> GetSpeeds(this List<ObjectMotion> motions) {
List<int> speeds = new List<int>();
foreach (ObjectMotion motion in motions) {
speeds.Add(motion.Speed);
}
return speeds;
}
This is "hard coded" and only serves a single property in a single object type. Its tedious and I'm sure there's a way using LINQ / Reflection to create an extension method that can do this in a generic and reusable way. Something like this:
public static List<TProp> GetProperties<T, TProp>(this List<T> objects, Property prop){
List<TProp> props = new List<TProp>();
foreach (ObjectMotion obj in objects) {
props.Add(obj.prop??);
}
return props;
}
Apart from the easiest method using LINQ, I'm also looking for the fastest method. Is it possible to use code generation (and Lambda expression trees) to create such a method at runtime? I'm sure that would be faster than using Reflection.
You could do:
public static List<TProp> GetProperties<T, TProp>(this IEnumerable<T> seq, Func<T, TProp> selector)
{
return seq.Select(selector).ToList();
}
and use it like:
List<int> speeds = motions.GetProperties(m => m.Speed);
it's questionable whether this method is better than just using Select and ToList directly though.
It is, no reflection needed:
List<int> values = motions.Select(m=>m.Speed).ToList();
A for loop would be the fastest I think, followed closely by linq (minimal overhead if you don't do use closures). I can't image any other mechanism would be any better than that.
You could replace the List<int> with a int[] or initialize the list with a certain capacity. That would probably do more to speed up your code than anything else (though still not much).
I am curious as to what restrictions necessitated the design decision to not have HashSet's be able to use LINQ's ForEach query.
What's really going on differently behind the scenes for these two implementations:
var myHashSet = new HashSet<T>;
foreach( var item in myHashSet ) { do.Stuff(); }
vs
var myHashSet = new HashSet<T>;
myHashSet.ForEach( item => do.Stuff(); }
I'm (pretty) sure that this is just because HashSet does not implement IEnumerable -- but what is a normal ForEach loop doing differently that makes it more supported by a HashSet?
Thanks
LINQ doesn't have ForEach. Only the List<T> class has a ForEach method.
It's also important to note that HashSet does implement IEnumerable<T>.
Remember, LINQ stands for Language INtegrated Query. It is meant to query collections of data. ForEach has nothing to do with querying. It simply loops over the data. Therefore it really doesn't belong in LINQ.
LINQ is meant to query data, I'm guessing it avoided ForEach() because there's a chance it could mutate data that would affect the way the data could be queried (i.e. if you changed a field that affected the hash code or equality).
You may be confused with the fact that List<T> has a ForEach()?
It's easy enough to write one, of course, but it should be used with caution because of those aforementioned concerns...
public static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach(var item in source)
{
action(item);
}
}
}
var myHashSet = new HashSet<T>;
myHashSet.ToList().ForEach( x => x.Stuff() );
The first use the method GetEnumerator of HashSet
The second the method ForEach
Maybe the second use GetEnumerator behind the scene but I'm not sure.
As the easiest way to convert the IList<T1> to IList<BaseT1>?
IList<T1>.Count() is very large number!!!
class BaseT1 { };
class T1 : BaseT1
{
static public IList<BaseT1> convert(IList<T1> p)
{
IList<BaseT1> result = new List<BaseT1>();
foreach (BaseT1 baseT1 in p)
result.Add(baseT1);
return result;
}
}
You'll get much better performance in your implementation if you specify the size of the result list when it is initalized, and call the Add method on List<T> directly:
List<BaseT1> result = new List<BaseT1>(p.Count);
that way, it isn't resizing lots of arrays when new items get added. That should yield an order-of-magnitude speedup.
Alternatively, you could code a wrapper class that implements IList<BaseT1> and takes an IList<T1> in the constructor.
linq?
var baseList = derivedList.Cast<TBase>();
Edit:
Cast returns an IEnumerable, do you need it in a List? List can be an expensive class to deal with
IList<T1>.Count() is very large number!!!
Yes, which means that no matter what syntax sugar you use, the conversion is going to require O(n) time and O(n) storage. You cannot cast the list to avoid re-creating it. If that was possible, client code could add an element of BaseT1 to the list, violating the promise that list only contains objects that are compatible with T1.
The only way to get ahead is to return an interface type that cannot change the list. Which would be IEnumerable<BaseT1> in this case. Allowing you to iterate the list, nothing else. That conversion is automatic in .NET 4.0 thanks to its support for covariance. You'll have to write a little glue code in earlier versions:
public static IEnumerable<BaseT1> enumerate(IList<T1> p) {
foreach (BaseT1 item in p) yield return item;
}