|
I store two kinds of data types (Bar1 and Bar2) in the same dictionary. Both data types dervies from Foo class. I would like to extract only the Bar2 elements from the dictionary.
Here is what I got:
abstract class Foo
{
}
class Bar1 : Foo
{
}
class Bar2 : Foo
{
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, Foo> foos = new Dictionary<string, Foo>();
for(int i = 0; i < 5; i++)
foos.Add("Bar1." + i, new Bar1());
for (int i = 0; i < 10; i++)
foos.Add("Bar2." + i, new Bar2());
List<Bar2> bar2List = new List<Bar2>();
foreach (Foo foo in foos.Values)
{
if(foo is Bar2)
{
bar2List.Add((Bar2)foo);
}
}
}
}
Are there any other method to extract the Bar2 elements from the dictionary into the Bar2 array (bar2List) instead of using foreach-loop and if-statment?
|
|
|
|
|
could give LINQ a whirl...
using System.Linq;
List<Bar2> bar2List = (List<Bar2>)foos.Values.Where(f => f is Bar2).ToList();
...it compiles but I didn't run it
If my jokes make me laugh, then I have already succeeded with 100% of my target audience
|
|
|
|
|
Didn't work: InvalidCastException...
Unable to cast object of type 'WhereEnumerableIterator`1[ConsoleApplication1.Foo]' to type 'System.Collections.Generic.List`1[ConsoleApplication1.Bar2]'.
Some other solution?
|
|
|
|
|
I think
List<Bar2> bar2List = foos.Values.Where(f => f is Bar2).ToList<Bar2>();
... should do it.
Linq-to-objects like this is essentially doing the same thing as the foreach loop in your original suggestion, so performance wise you will gain nothing, but some people will say that the Linqed code is more readable (and in this case I think I'd agree with that).
(Ed: putting the type parameter on Where doesn't work, it tries to cast items before checking them.)
|
|
|
|
|
You cando this with LINQ
List<Bar2> bar2s =
(from entry in foos
where entry.Value is Bar2
select entry.Value as Bar2).ToList();
If you don't care about the list being of Bar2, you can just do this:
var bar2s = from entry in foos
where entry.Value is Bar2
select entry.Value;
Not sure what the performance comparision is like, but my gut instinct is to go with the cleaner code unless I know performance is a concern.
|
|
|
|
|
Do they really have to come from that combined dictionary? Couldn't you keep a separate list of bar2?
|
|
|
|
|
List<Bar2> bar2List = foos.Values.OfType<Bar2>().ToList();
Of course, internally it's pretty much just doing the same foreach loop you're doing, so don't expect it to be much more efficient.
|
|
|
|
|
Whats wrong with a foreach loop? Do you care about speed / performance or do you care about writing elitist LINQ code or some other fancy method to impress somebody? No matter what method you use, at some level, its going to have to do a foreach loop, so why not cut out the middle man for performance reasons? People who use LINQ for every little thing often end up ripping it out down the road cuz its often much slower then just writing "normal" code. True Story.
|
|
|
|
|
Hear hear!
And the foreach is more readable.
|
|
|
|
|
SledgeHammer01 wrote: Whats wrong with a foreach loop?
I <now> find the List<>.Where syntax in 1 line much more readable than 5 lines of a well laid out foreach code.
I don't consider Linq elitist, then again I only use the simplest Linq and will resort to normal style if it gets too complex or it looks like taking too long to work out the Linq syntax.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Yeah, but my 5 line foreach loop is 2x to 3x faster then your 1 line LINQ . Don't get me wrong, I sometimes use LINQ myself. I was just pointing out that in this case, it is silly of the OP to use LINQ over a basic foreach.
|
|
|
|
|
SledgeHammer01 wrote: 2x to 3x faster then your 1 line LINQ
I was not aware the different was so great, I like the firstordefault for locating an object in a List<> especially in SL where it is asynch processing
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hello,
Does anyone knows a form navigation framework that i can use in order to implement a winform application that shows a main form displaying a list of options, each option displays a different form, which in turn display a list of options and so on ?
It is similar to wizard but with more hierarchies.
Thanks,
Berlus
|
|
|
|
|
I don't think there is a framework for navigation in winforms, it is such a simple process a framework is hardly required. You don't need to support browser crap so just show the form you need to see!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
As Mycroft states a framework isn't really necessary; however, the wizard controls can be used and navigation can be modified based on user input.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Hi, I created custom control derived from UserControl and added a button on it.And I added a second button and docked it to the first button.
Question is: When the first button draws/paint well at runtime, the second button sometimes is absent, not visible. It only shows up when mouse enters the invisible area
Thanks in advance
|
|
|
|
|
It works fine for me. You haven't provided any details about how this control is setup, how it's drawn, if you're using any threading, if you're painting stuff on the control yourself, ...
|
|
|
|
|
Hi,
I need to design a program should be able to update certain textbox for each event inside the GUI and after every 10 seconds of most recent event, text tox should be back to original value..Let say
<br />
Event one occurs --> text box updated --> after 10 seconds --> text box back to normal
This is the case in perfect world, but it might be possible that someone create another GUI event during this period of 10 seconds..
Event one occurs --> text box updated --> after 8 seconds --> event two occurs --> GUI updated --> after 2 seconds the other thread (10 seconds completed for first event), text box back to normal.
So in this case, for second event, the textbox get back to original value in just 2 seconds. I know I could use thread intrupt to cancel the other thread. But my question is, it the best way of doing it?? And what is there any other way to starting intrupped thread again, without making a new thread? Will thread intrupt make sure everything will go perfect?? Would you suggest some more efficient way? I may be misunderstanding about threading here, please forgive that. Any suggestions, links or comments will be appreciated.
PS
So far my code is like this..
Thread t = new Thread(keep_run);
public void update()
{
t.Interrupt();
if (MessageLbl.InvokeRequired)
{
MessageLbl.Invoke(new setText(() => MessageLbl.Text = "User settings have been updated."));
}
else
{
MessageLbl.Text = "User settings have been updated.";
}
t = new Thread(keep_run);
t.Start();
}
private void keep_run()
{
try
{
Thread.Sleep(10000);
MessageLbl.Invoke(new setText(() => MessageLbl.Text = "Welcome to MAT Downloader"));
}
catch { MessageBox.Show("Interrupted"); }
}
}
If you find any other problems with the code then do mention them.
Thanks
Regards,
Shivam Kalra
|
|
|
|
|
Is it really necessary to resort to threads here?
And if the answer is yes, then more specifically, is it really necessary to resort to multiple GUI-altering threads?
Why not just make the main (GUI) thread have a method that updates the text box and a Timer control that triggers after 10 seconds to reset the contents of the text box.
When a new text-event occurs, your method is called again, and you reset the timer to 10 seconds again.
Something in the way of (incomplete code):
void AddNotification(string NotifyText)
{
Timer1.Enabled = false;
MessageLbl.Text = NotifyText;
Timer1.Enabled = true;
}
void Timer1_Timer(object sender)
{
Timer1.Enabled = false;
MessageLbl.Text = "Default text here";
}
With Timer1's timeout set to 10 seconds. If your GUI thread is doing some intensive work, then the timer might not fire until after the work is done. If that is a problem, thát would be the time to use threads, to do the work in a background thread while the GUI remains responsive.
All in all, it's best to have the main thread handle all GUI.
|
|
|
|
|
So I have a code to connect to NamedPipeServerStream, code works fine but after closing the Form, Connect never throws exception and Application do not ends.
void BeginConnect()
{
new Thread(new ThreadStart(delegate()
{
NamedPipeClientStream client = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut);
try
{
client.Connect(5000);
}
catch (TimeoutException ex)
{
}
catch (IOException ex)
{
}
BeginConnect();
})).Start();
}
One more thing, why this simple code taking more than 50% CPU
edit :
Found a workaround, http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/7bbf5a0b-3c22-4836-b271-999e514c321b/[^]
TVMU^P[[IGIOQHG^JSH`A#@`RFJ\c^JPL>;"[,*/|+&WLEZGc`AFXc!L
%^]*IRXD#@GKCQ`R\^SF_WcHbORY87֦ʻ6ϣN8ȤBcRAV\Z^&SU~%CSWQ@#2
W_AD`EPABIKRDFVS)EVLQK)JKQUFK[M`UKs*$GwU#QDXBER@CBN%
R0~53%eYrd8mt^7Z6]iTF+(EWfJ9zaK-iTV.C\y<pjxsg-b$f4ia>
-----------------------------------------------
128 bit encrypted signature, crack if you can
modified on Sunday, June 26, 2011 12:17 AM
|
|
|
|
|
I have some LinkLabel controls in a Windows Form. When the user clicks a LinkLabel the application displays a form containing data pertaining to the object selected, determined by the LinkLabel's text. The form is not displayed as a dialog and it is not maximized by default. The behavior I would like to achieve is once the user clicks out of the popup form (for example, he/she clicks another area in the application's main form) the popup form should disappear.
I have tried subscribing to the form's LostFocus event and creating the event handler for it. However, when I click away from the form, it simply goes behind the application form. Is LostFocus not the appropriate event? Or should I handle this in the popup form rather than from the "caller" form?
|
|
|
|
|
Have you tried putting form.Close() in the popup form's Deactivate() event?
CQ de W5ALT
Walt Fair, Jr., P. E.
Comport Computing
Specializing in Technical Engineering Software
|
|
|
|
|
No, I have not. I will do that though. Thanks.
|
|
|
|
|
Hi,
I'm trying to populate a listview control and my query is LINQ. I used one of the table (Production.Product) of AdventureWorks database.
At first i have problem populating the header, but i figured it out after an hour. The code below is the code on how to populate column in listview using LINQ.
Code:
----------------------------------------------------------------------------------------------
ProductID Name ProductNumber MakeFlag FinishedGoodsFlag Color
----------------------------------------------------------------------------------------------
317 LL Crankarm CA-5965 0 1 Black
318 ML Crankarm CA-5938 0 1 Black
319 HL Crankarm CA-5990 0 1 Black
320 Chainring CA-5932 0 1 Black
---------------------------------------------------------------------------------------------
DataClasses1DataContext db = new DataClasses1DataContext();
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
DataRow dr;
var products = from p in db.Products
where p.Color != null
select p;
#region getHeader
var headers = products.First();
foreach (var columnHeader in headers.GetType().GetProperties())
{
lvw.Columns.Add(columnHeader.Name);
}
#endregion
Now, my problem is how do i populate the result of my query and add it to listview. Actually, i can populate it like this,
ListViewItem lstItem = null;
foreach (var itms in products)
{
lstItem = new ListViewItem(itms.ProductID.ToString());
lstItem.SubItems.Add(itms.Name);
lstItem.SubItems.Add(itms.ProductNumber);
..... and so on
}
The problem on the above code is that, what if i have a 25 columns in my query result? I have to type in my code 25x the lstItem.SubItems.Add(value) which kinda hassle for me. I want my function in populating the listview to be dynamic.
Anyone out there can help me to solve my "simple (i think)" problem.
Thanks and regards
Jessie
if(you type your code here) {
Messagebox.Show("You help me a lot!");
}
else {
You help me = null;
}
|
|
|
|
|
ListView is quite limiting control. You can take a look on this extended ListView control A Much Easier to Use ListView[^] that supports data binding.
Hope it helps.
M.
|
|
|
|