GUI optimize nested foreach [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Can anyone assist on below WPF GUI how to convert to Linq due to low performance:
foreach (Grid b in main_grid.Children)
{
foreach (Control s in b.Children)
{
if (s.GetType() == typeof(Button))
{
if (s.Tag.ToString() == message)
{
if (status == "OIRS_INUSE")
{
s.Background = Brushes.Orange;
}
else
{
s.Background = defaultBackground;
}
}
}
}
}

First, you are asking the wrong question. Linq doesn't help.
One way to speed up this loop is to reduce the workload of its bottleneck:
foreach (Grid b in main_grid.Children)
{
foreach (Control s in b.Children)
{
if (s.SomeEnumValue == SomeEnum.Value)
{
s.Background = Brushes.Orange;
}
else
{
s.Background = defaultBackground;
}
}
}
First comparison if (s.GetType() == typeof(Button)) is costly:
for 100 million calls:
typeof(Test): 2756ms
TestType (field): 1175ms
test.GetType(): 3734ms
you'll have more than 5 times slower than a simple field comparison.
Second comparison if (s.Tag.ToString() == message) and third comparison status == "OIRS_INUSE" are costly
Moreover, the second comparison contains a ToString method which has its own cost.
So get rid of all these expensive comparisons and replace them with a simple field comparison such as an enum which is cheap.

Related

Fill Enumerable Inside Enumerable in .NET 5 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a "Panel" model that has multiple "Panel Pages". I would like to get a list of all panels, and fill each panel with its respective "Panel Pages".
Here is my code currently (that works):
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
var customPanels = _customPanelService.GetDynamicCustomPanels();
var dynamicCustomPanels = customPanels.ToList();
foreach (var customPanel in dynamicCustomPanels.ToList())
{
var customPanelPages = _customPanelPageService.GetCustomPanelPages(customPanel.PanelGUID.ToString());
customPanel.CustomPanelPages = customPanelPages;
}
return dynamicCustomPanels;
}
How do I do this in an minimal amount of lines?
This should work:
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
return _customPanelService.GetDynamicCustomPanels().Select(p => {
p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
return p;
});
}
That's technically 3 statements (two returns and an assignment) and one block, though it's kind of an abuse of the Select() method. I might write it like this instead:
public IEnumerable<DynamicCustomPanel> GetCustomPanels()
{
foreach(var p in _customPanelService.GetDynamicCustomPanels())
{
p.CustomPanelPages = _customPanelPageService.GetCustomPanelPages(p.PanelGUID.ToString());
yield return p;
}
}
Which is... also 3 statements (counting foreach) and one block, just spaced different to use one more line of text.

I have a question of understanding in ConcurrentDictionary [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a question of understanding. Which is the better option in terms of safety and performance?
private ConcurrentDictionary<string, ProfitTarget> chartTraderTP;
if (chartTraderTP.ContainsKey(orderId))
{
//Store values for later use in Mouse Events
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
//We can draw the Rectangle based on the TextLayout used above
if (!chartTraderTP[orderId].IsMovingOrder
&& (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own
|| ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP, tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP, tpOutlineBrushDx,
LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText, tpTextLayout, tpTextBrushDx,
SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
}
or
private ConcurrentDictionary<string, ProfitTarget> chartTraderTP;
//Store values for later use in Mouse Events
if (chartTraderTP.ContainsKey(orderId))
{
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
}
//We can draw the Rectangle based on the TextLayout used above
if (chartTraderTP.ContainsKey(orderId) && !chartTraderTP[orderId].IsMovingOrder
&& (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own
|| ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP, tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP, tpOutlineBrushDx,
LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText, tpTextLayout, tpTextBrushDx,
SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
The code is executed very often, and I would like to make the access as fast as possible but still threadsafe.
Neither are safe, as you're performing multiple operations while assuming the collection isn't changing between operations, which is not a safe assumption.
Since you want to use a number of different operations and need entire section to be logically atomic, just use a regular Dictionary and lock around the access to it.
lock (chartTraderTP)
{
//Store values for later use in Mouse Events
chartTraderTP[orderId].OrderLabelRectText = rectTextOrderLabelTP;
//We can draw the Rectangle based on the TextLayout used above
if (!chartTraderTP[orderId].IsMovingOrder && (ChartTraderDisplayStyle == ChartTraderDisplayStyle.Own || ChartTraderDisplayStyle == ChartTraderDisplayStyle.Both))
{
RenderTarget.FillRectangle(rectTextOrderLabelTP, tpAreaBrushDx);
RenderTarget.DrawRectangle(rectTextOrderLabelTP, tpOutlineBrushDx, LabelOutlineWidthTP);
RenderTarget.DrawTextLayout(vectText, tpTextLayout, tpTextBrushDx, SharpDX.Direct2D1.DrawTextOptions.NoSnap);
}
}

Codility test result unclear [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I solved this codility test with the following code:
private static int lesson2_1(int[] A) {
if (!Isvalid(A))
{
return -1;
}
List<int> d = A.Distinct().ToList();
foreach (var item in d)
{
var q = from one in A where one == item select one;
if (q.Count() == 1)
{
return item;
}
}
return -1;
}
private static bool Isvalid(int[] a)
{
if (a.Length == 0)
{
return false;
}
return true;
}
These are the results:
I do not know how to approach this, since I have not learned yet about complexity. Can someone please guide me to the right approach to this issue?
Many thanks
My advice - don't reinvent the wheel. .Net has a lot built into it. Chances are unless you have specialist requirements Microsoft will be able to implement it better than you. The following gets a 100% score:
using System;
using System.Linq;
class Solution {
public int solution(int[] A) {
return A.GroupBy(a => a).First(a => a.Count() %2 == 1).Key;
}
}
There are a few issues with your solution.
1) You aren't following the test spec. It states
all but one of the values in A occur an even number of times.
That means that the number you are looking for could occur, 3,5,7,etc. times - you are just checking for 1.
2) The time complexity of your solution is poor. You are looping through every item and doing a search for each item within every loop. This isn't necessary if you think about it. You will have to go through every item in the list but if you process it as you go along you effectively only have to go through each item once and then the buckets of each item once.

Can i use operator 2 operators in a If statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How can i use 2 operators in a if statement. I have the following method and the MinSaldo cant be lower then 1000 dollar but i cant use 2 operators in a if statement how can i fix this ?
public void MinSaldo(double Money)
{
if (saldo - money < MinSaldo )
{
throw new Exception("saldo low ");
}
else
{
messagebox.show("works");
}
}
Yes, you can use as many as you want by combining them with the operators: and (&&), or (||).
In this case
public void MinSaldo(double Money)
{
if (MinSaldo < 1000 || saldo - money < MinSaldo )
{
throw new Exception("saldo low ");
}
else
{
messagebox.show("works");
}
}

I want my if loop to do nothing if certain conditions are met [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i want my if loop to do nothing when the conditions that i gave it are there
i'm new to C# and winform so i searched the internet but didnt find an answer that seems to work and right now i have no idea what to do.
,Mo
screenshot of the loop
If I understand your question correctly, you want to "cancel" all operations in the current method, right? You can use return; to do that:
if(value2 == null) return;
There is just one other thing wrong with your code: value2 will never be null.
decimal value2;
if(!decimal.TryParse(result[1], out value2)) return;
should work a lot better ;)
I can't see any loop in the code provided. You want to change Parse to TryParse and use return in order to return from the method (== do nothing):
public void button14_Click(Object sender, EventArgs e) {
string[] result = input1.Text.Split(Oprator);
//TODO: it may appear, that you want TryParse here as well
decimal value1 = decimal.Parse(result[0]);
decimal value2;
// If you have too few items, and thus you have no "value2" - do nothing
if (result.Length < 2)
return;
// Try parse result[1] to decimal; if parse fails (e.g. result[1] == "zzz") - do nothing
if (!decimal.TryParse(result[1], out value2))
return;
// you have value1, value2, Oprator; put required logic here
switch (Oprator) {
...
}
}
Have you thought about a "While" loop?
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}

Categories

Resources