|
You can do
public class Jef {
public int a;
public int b;
}
public class Test {
List<Jef> list = new List<Jef>();
private void test1() {
list.First().b = 13;
list.First(j => j.a == 12).b = 14;
}
}
when Jef is a class, as list.First() then returns the reference of a Jef object. And when null, it would throw a NullRefExc.
You can't when Jef is a struct, as structs are value types, there is no reference or pointer to a value type.
With structs the compiler rightfully gives the error: cannot modify the return value of ... because it is not a variable.
Furthermore, I'm wondering what you expect from FirstOrDefault as a target for assignment: when no items match, the default would be what? where would the new value have to go?
|
|
|
|
|
On the FirstOrDefault , I know it's there because it's an update API. But now that you have my wheels turning, if multi-user and the sub category is deleted, then it fails.
Category is a class.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
How about:
int index = cR.SubCategories.IndexOf(subCategory);
if (index == -1)
{
cR.SubCategories.Add(subCategory);
}
else
{
cR.SubCategories.RemoveAt(index);
cR.SubCategories.Insert(index, subCategory);
} Or:
int index = cR.SubCategories.IndexOf(subCategory);
if (index == -1)
{
cR.SubCategories.Add(subCategory);
}
else
{
cR.SubCategories[index] = subCategory;
}
Unfortunately, to assign to the value returned from a method, you'd need a ref return[^]. And you can't do that with a List<T> , so you'd have to implement your own list class.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
modified 18-Oct-19 8:06am.
|
|
|
|
|
Just for fun, here's a simplistic - and not thoroughly tested! - example using ref returns:
public readonly struct SubCategory : IEquatable<SubCategory>
{
public SubCategory(int id, string name) => (Id, Name) = (id, name);
public int Id { get; }
public string Name { get; }
public override int GetHashCode() => Id;
public override bool Equals(object obj) => obj is SubCategory other && Equals(other);
public bool Equals(SubCategory other) => Id == other.Id;
}
public class SubCategoryList : IEnumerable<SubCategory>
{
private SubCategory[] _categories = new SubCategory[4];
private int _length;
public int Count => _length;
public int Capacity => _categories.Length;
public ref SubCategory this[int index] => ref _categories[index];
public ref SubCategory FindOrAdd(int id)
{
for (int index = 0; index < _length; index++)
{
if (_categories[index].Id == id)
{
return ref _categories[index];
}
}
Add(new SubCategory(id, null));
return ref _categories[_length - 1];
}
public void Add(SubCategory value)
{
if (_length == _categories.Length)
{
int newSize = _length * 2;
Array.Resize(ref _categories, newSize);
}
_categories[_length] = value;
_length++;
}
public IEnumerator<SubCategory> GetEnumerator()
{
SubCategory[] categories = _categories;
int length = _length;
for (int index = 0; index < length; index++)
{
yield return categories[index];
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class Category
{
public SubCategoryList SubCategories { get; } = new SubCategoryList();
} Usage:
var cR = new Category
{
SubCategories =
{
new SubCategory(1, "C1"),
new SubCategory(2, "C2"),
new SubCategory(3, "C3"),
}
};
cR.SubCategories.FindOrAdd(2) = new SubCategory(2, "X2");
cR.SubCategories.FindOrAdd(42) = new SubCategory(42, "Z42"); NB: I wouldn't recommend using this approach.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Wow, that was an explosion of thought!
I knew I could edit my class to help out, but it's been awhile since I've done it.
This expands on Luc's thought in using struct and class. I've never used struct or have heard of it.
But me going NoSQL, I can see where this is going to be a requirement for me to learn, now that I'm building a store and getting more complex with using data.
I need time to adsorb this new info.
Thanks Richard and Luc!
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
So I was having trouble with my Angular Category program in which I would update a categories subCategory and it would add a subCategory or update the wrong one with remove and add, and IndexOf.
So I pickup a Category Model in the API via HTTPGet and send it to Angular. Then I send just the SubCategory model within Category back to a different API via HTTPPut. In this API, I pick up the Category from MongoDB, then do var index = category.SubCategories.IndexOf(subCategory); and index returns -1. So I did a First to get the index
var index = category.SubCategories.IndexOf(category.SubCategories.First(sc => sc.Id == subCategory.Id));
and I get 2 back which is correct.
So in my other modules, I can pass a model to Angular, work on it and pass it back no problem. I suspect if I would of passed back the Category in whole the IndexOf(subCategory) would of worked.
I'm just curious about this. Perhaps an explanation or knowledge will help create better designs.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Hi ,
I created an application (windovs form) where in the background of the application ping devices and report the results if they are online. The application works when it starts up, but I need to refresh this code every 1 min. means once i turn on the windovs form it stays on all the time,but my data (label) refreshes every 1 min and prints new ping results.
Thanks in advance
an example of my code that I used to ping
InitializeComponent();
Ping ping = new Ping();
PingReply pingresult = ping.Send("10.10.9.15");
if (pingresult.Status.ToString() == "Success")
{
label1.Text = "Povezan";
label1.ForeColor = System.Drawing.Color.Green;
label32.ForeColor = System.Drawing.Color.Green;
label32.Text = ('\u263b').ToString();
}
else
{
label1.Text = "Prekid";
label1.ForeColor = System.Drawing.Color.Red;
label32.ForeColor = System.Drawing.Color.Red;
label32.Text = ('\u2639').ToString();
SoundPlayer simpleSound = new SoundPlayer(@"c:\Windows\Media\Alarm09.wav");
simpleSound.Play();
this code is required to rotate every 1 min and print new results
|
|
|
|
|
Take a look at System.Windows.Forms.Timer class and event Tick . That would do what you need.
"It is easy to decipher extraterrestrial signals after deciphering Javascript and VB6 themselves.", ISanti[ ^]
|
|
|
|
|
Hmm. That sure is the easiest way, but it would severely degrade app responsiveness when Ping.Send() is awaiting a reply and possibly times out. Yes one can use an overload that offers a timeout parameter, however IMO there isn't a timeout value that is sufficiently long for Ping not to give false negatives, and at the same time sufficiently small for the app to remain fully responsive.
So for a periodic Ping to a constant address I would recommend using a separate Thread, with a forever loop holding Ping.Send() and a Thread.Sleep(); and then a simple bool variable could offer the latest state. Simple variables can safely be accessed across thread boundaries, no locking or other synchronization would be required.
|
|
|
|
|
Why not use an async method combined with Ping.SendPingAsync[^]?
private void OnPingSuccess()
{
...
}
private void OnPingFailure()
{
...
}
private async Task MonitorServer(IPAddress address, TimeSpan frequency, CancellationToken cancellationToken)
{
Ping ping = new Ping();
while (!cancellationToken.IsCancellationRequested)
{
PingResult result = await ping.SendPingAsync(address);
if (pingresult.Status == IPStatus.Success)
{
OnPingSuccess();
}
else
{
OnPingFailure();
}
await Task.Delay(frequency, cancellationToken);
}
}
private CancellationTokenSource _cancellationTokenSource;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_cancellationTokenSource = new CancellationTokenSource();
_ = MonitorServer(IPAddress.Parse("10.10.9.15"), TimeSpan.FromMinutes(1), _cancellationTokenSource.Token);
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed();
_cancellationTokenSource?.Cancel();
} The OnPingSuccess and OnPingFailure methods should be able to directly update the UI, because they'll be running on the UI thread.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thanks Richard. That looks interesting. I had been considering async /await but am unfamiliar with it; also I'm not afraid of going all in with new Thread() . Your async approach seems like a lot of code...
|
|
|
|
|
Most of it's about handling cancellation when the form closes. Which you'd need to do with a background thread as well.
Plus you have the added advantage that you can update the UI from the async method, without having to monitor changes to a variable or mess around with Invoke or synchronization contexts.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
All true. I set Thread.IsBackground true, and typically have a global public static bool AppIsExiting which I test in my forever loops. That takes care of most of the potential termination problems. Your approach is cleaner of course, mine dates back 20 years...
|
|
|
|
|
Check out System.Reactive
.NET Foundation Reactive Extentions[^]
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
hi, does in c# exist a type of variable that is like pointers in c++?
I mean, in c++, if I use a pointer to a byte, I can add 1 to this pointer and, in this way, move it along all the array, in c#, is there a way to do a similar thing?
Thank you.
|
|
|
|
|
Yes. They are called "pointers": Pointer types - C# Programming Guide | Microsoft Docs[^]
Do note that you need to specify unsafe for yoru code in order to use them, and you need to take precautions that the memory won't be moved by the GC while you are using the pointers. If you don't need 'em, don't use 'em: and that's "real need" not "I need this to be like my C++ code".
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
There's no need to do things like that in c#, so if you find yourself doing things like that then you probably need to rethink your solution and find one more suitable to the language.
|
|
|
|
|
Just declare a byte[] type and you can access the content in a similar way, although by index value rather than using pointer arithmetic.
|
|
|
|
|
|
Yes. Pointers do exist in C#
Refer this link for pointers in C#: Pointers in C#
modified 25-Oct-19 4:28am.
|
|
|
|
|
Mucking around with DataGridView, DataTable, DataView: this works, but, I suspect there's a better way to do this:
private void btnSave_Click(object sender, EventArgs e)
{
if (dt != null)
{
DataTable dtbl = dt.Clone();
if (dView != null)
{
foreach (DataRowView vrow in dView)
{
dtbl.ImportRow(vrow.Row);
}
}
dtbl.WriteXml(... filepath goes here .xml ... );
}
}
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
|
|
|
|
|
How about using the ToTable method on the view?
DataView.ToTable Method (System.Data) | Microsoft Docs[^]
if (dt != null)
{
DataTable dtbl = dView != null ? dView.ToTable() : dt.Clone();
dtbl.WriteXml(...);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thanks !
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
|
|
|
|
|
Hallo, I'm trying to extract images from pdf.
The problem is with some images that, in pdf, are with the attribute Predictor. I think that, with this attribute, the resultant bytes are to be decoded with png algorith, but I don't find it.
Another problem is with images that are with 8 bit indexed, in the pdf file I don't file the palette, as in other pdf files. Is there someone who is expert with pdf images? I hope my question is understandable. Thank you.
|
|
|
|
|
Hi,
you seem to be peeking into the PDF file to extract what you need, and that is bound to give you surprises when several different PDF sources are involved.
There is another way to approach things, that may or may not meet your needs: using something like Ghostscript[^] you can get an image of a particular page of a PDF document (in any resolution you want), then operate on that.
The advantage is you don't need to deal with all the possible ways PDF stores/creates images; the disadvantages are (1) you only get the resolution you asked for and (2) if all you need is a picture you still have to locate it and extract it from the page image.
Hope this helps.
|
|
|
|