|
Sorry Bill, but it seems you are indulging in the festivities of the new year a tad early.
*You* claimed ToList() does not create a new list when it in fact does. Value types will of course be copied and reference types will of course be referenced. However, it is not the instance of the list that you think it is. Thus you will run into situations like I have shown you as well as others.
While my example trivially used lst.ToList() for simplicity, if you got off your condescending high horse for a second, you'd realize that LINQ operations operate on IEnumerable sequences. Of which ListT is one. However, IEnumerableT is not a ListT.
Since I'm sure you'll retort with one of your childish condescending replys, I'll leave you with this C&P from MSDN:
The ToList<tsource>(IEnumerable<tsource>) method forces immediate query evaluation and returns a List<t> that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.
ToArray<tsource> has similar behavior but returns an array instead of a List<t>.
Drop the cocky attitude kid, you might learn something.
Bye .
|
|
|
|
|
BillWoodruff wrote: The result of a Linq statement is not a "concrete instance" of a generic List
Correct; it's an IEnumerable.
BillWoodruff wrote: by, for example, using 'foreach
No; that's not a problem.
BillWoodruff wrote: or using .ToList
Exactly. That's what you're doing. ToList is making a concrete copy -- your library code should not being using ToList; it should just be returning the IEnumerable, the same as the Linq methods do. If the final output should be a List or Array or whatever, that should be done as late as possible, by the application, not by library routines that don't know how the output will be used.
|
|
|
|
|
Happy New Year, Piebald !
I am a fan of late-binding as late as possible, so I'm in step with you on that point. And, as I commented to Mighty Hammer, the code I write here is meant to be "educational;" it's not the same code I might write were I part of a team of other programmers, all of whom were using some library class I wrote: in that scenario I might well have the method return only the Linq structure, not return the "instantiated" List.
Where I believe I diverge in opinion re the result of a Linq query after its evaluation/rendering into "final form" requires a distinction between a Linq query that returns a bunch-of/sequence-of Values rather than References.
So I'd argue that a Linq query that returns a bunch of selected/filtered pointers to Class instances rendered into a generic List of said Classes: does not make a copy in the sense of a "deep copy;" rather, it just wraps a bunch of pointers to said instances in a List.
However, a Linq query rendered to a List that returns a set of integers, or strings: yeah, them are copies.
Does this clarify anything ?
cheers, Bill
«A man will be imprisoned in a room with a door that's unlocked and opens inwards ... as long as it does not occur to him to pull rather than push» Wittgenstein
|
|
|
|
|
Not really. Did you forget that structures are value types too? And thus you'll get a copy of them? Oh hey... look at that, Point is actually a structure and not a class. So is Rect and various other things that people usually treat as classes when they are actually structures.
EDIT: BTW, yes, I realized in your example Point is inside of a class which is a bit different.
|
|
|
|
|
Your abilities for off-topic ramblings are truly impressive. My reply to PieBald mentioned nothing about .NET objects like Structs; and I am very aware of the .NET objects which are Structs, Point, Rect, etc., and the fact that Structs are internally handled as a Value Type.
I specifically talked about instances of Classes as an example of how a Linq query will create a wrapper around a set of references-to instances, not copies-of instances, for certain Object Types.
I hope this is just a phase you are going through
«A man will be imprisoned in a room with a door that's unlocked and opens inwards ... as long as it does not occur to him to pull rather than push» Wittgenstein
|
|
|
|
|
BillWoodruff wrote: the code I write here is meant to be "educational;"
Then please don't lead newbies down the rabbit hole of bad Linq -- show them only the One True Path because they will think your code is "best practice".
BillWoodruff wrote: does not make a copy in the sense of a "deep copy;"
It's still a needless copy; it's still very bad, and newbies won't know the difference.
Furthermore, if your method is generic, unless it specifies a struct constraint), it won't know whether the data is value-type or not. In practice, it's not a worthwhile distinction; don't make any needless copies of anything.
Furthermore, consider some collection and a chain of n Linq/Lambda filters, each of which returns a List rather than a simple enumerator. You've copied the each datum (values or references I don't care) n times.
With the same n tasks performed with only one ToList at the end, you copy each datum only once.
-- The foregoing is likely over-simplified and not strictly true, because the enumerators involved also copy the data one-by-one as it passes through, so perhaps there are 2n copies "your way" and n+1 copies "my way".
Another thing I want to point out is that the final task might be "take 10" (or similar) which means "my way" only iterates and copies those 10 data, not all of them -- whereas calling ToList at intermediate steps will cause a lot of needless intermediate copying.
|
|
|
|
|
I think you are generalizing from speculating about advanced use-case scenarios to some unwarranted conclusions about potential confusion for beginners in understanding how Linq operates.
Yes, there is confusion about Linq operates, and, yes, beginners to using Linq do get confused trying to form a "mental model" of its internal dynamic operation which is useful. And, certain Linq concepts and operators like "Yield return," and the use of 'New are ... imho ... just difficult to "get down."
I find it significant that one of the most popular books on Linq (Albahari's) is one of the worst technical books I've ever seen; however, Albahari's LinqPad tool is a great resource.
The specific example I gave here may have given you an occasion to vent your spleen, and enjoy spouting off the typical kind of blanket put-down that often characterizes your responses here on CodeProject, but, I consider that "your curmudgeonly thing," and, honestly, I'm not really disturbed by it; I find it entertaining on one level. Perhaps because I get into "curmudgeonly" myself !
However, I don't want to let the hot volcanic mud you discharge out your deep-sea smoking fumarole confuse other people.
Anyone who thinks they know the "one true path" to, or from, anywhere, is ... truly ... lost
Happy New Year ! Bill
«A man will be imprisoned in a room with a door that's unlocked and opens inwards ... as long as it does not occur to him to pull rather than push» Wittgenstein
|
|
|
|
|
Message Closed
modified 29-Dec-14 11:11am.
|
|
|
|
|
Hi all, I am pretty new to coding, and am attempting to port this code from C to c#, and cannot figure out the createfile section. Do i need it? can i replace it with something?
original C.
HANDLE openAndSetupComPort(const TCHAR* comport)
{
HANDLE com_handle;
DCB dcb_serial_params = { 0 };
COMMTIMEOUTS timeouts = { 0 };
DWORD com_error;
COMSTAT comstat;
com_handle = CreateFile(comport,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (com_handle == INVALID_HANDLE_VALUE){
printf("Error opening port\n");
return INVALID_HANDLE_VALUE;
}
dcb_serial_params.DCBlength = sizeof(dcb_serial_params);
if (!GetCommState(com_handle, &dcb_serial_params)){
printf("Failed to get the previous state of the serial port\n");
CloseHandle(com_handle);
return INVALID_HANDLE_VALUE;
}
dcb_serial_params.BaudRate = 115200;
dcb_serial_params.ByteSize = 8;
dcb_serial_params.StopBits = ONESTOPBIT;
dcb_serial_params.Parity = NOPARITY;
if (!SetCommState(com_handle, &dcb_serial_params)){
printf("Failed to set the serial port's state\n");
}
timeouts.ReadIntervalTimeout = -1;
timeouts.ReadTotalTimeoutConstant = 100;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 100;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(com_handle, &timeouts)){
printf("Failed to set the timeouts\n");
CloseHandle(com_handle);
return INVALID_HANDLE_VALUE;
}
Sleep(300);
ClearCommError(com_handle, &com_error, &comstat);
if (comstat.cbInQue != 0){
PurgeComm(com_handle, PURGE_RXCLEAR | PURGE_TXCLEAR);
}
return com_handle;
}
which is being called here:
if(!WriteFile(com_handle, write_bytes, sizeof(write_bytes), &bytes_written, 0)){
printf("Error writing to port\n");
return 2;
}
So I am opening a serial port:
public static void SerialSetupIMU()
{
_serialPort = new SerialPort();
_serialPort.PortName = "COM11";
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.ReadTimeout = 100;
_serialPort.WriteTimeout = 100;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
try
{
_serialPort.Open();
_serialPort.DiscardInBuffer();
_serialPort.DiscardOutBuffer();
}
catch
{
Console.Write("port does not exist");
}
if (_serialPort.IsOpen)
Console.Write("port 11 opened");
}
and attempting to write:
_serialPort.Write(com_handle , write_bytes, byteSize, bytes_written, 0);
And it fails on the 'com_handle', obviously, because I haven't added it. But what is it expecting there?
Any help would be much appreciated!
Thank you much.
|
|
|
|
|
C# is an object oriented language, C isn't.
When you create and open the SerialPort object it "remembers" which port handle it should use internally, so you don't need to think about it - you just tell the SerialPort instance to write, and it sorts it all out for you: http://msdn.microsoft.com/en-us/library/ms143551(v=vs.110).aspx[^]
So, once you have the port opened, just write your data to it:
_serialPort.Write(write_bytes, 0, write_bytes.Length); Will write all the bytes in the write_bytes array to the port.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks for your answer!
_serialPort.Write(write_bytes, 0, write_bytes.Length);
is giving me a
'no overload for method takes 3 arguments' exception.
|
|
|
|
|
actually, my bad. that is working great. thanks again!
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Hi,
Regarding sqlConnection, is it recommended to keep it open all across the application or open it every time I want to use it then close it? Which method is better for the memory?
Thanks,
Jassim
Technology News @ www.JassimRahma.com
|
|
|
|
|
Forget memory, it's pretty much irrelevant for SqlConnection objects.
Close it when you are finished with it, and Dispose the object.
The actual connections at the other end (SQL Server) are scarce resources, and holding yours open for the duration of your application can "block" others from accessing the database at all. So release it when you are finished, which lets other users have it and you can get it back later.
And Dispose any SqlCommand objects you create as well!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
In your methods that require a SqlConnection ensure you use a using block to enclose your connection related code. Objects that implement the IDispose interface (of which SqlConnection does) is guaranteed to be disposed when completed.
using (SqlConnection conn = new SqlConnection())
{
}
"There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult." - C.A.R. Hoare
Home | LinkedIn | Google+ | Twitter
|
|
|
|
|
Im Making a very simple vehicle renting program as learning task.
This is probably a simple question even if the text is a bit long.
I have made theese simple classes.
Vehicle, VehicleManager, VehicleForm with (Add/Remove buttons)
Customer, CustomerManager, CustomerForm(Add/Remove buttons)
Agreement, AgreementManager, AgreementForm(with Add/Remove buttons
one ComboBox with Customers and
one ComboBox with vehicles
(and 2 datepickers))
In AgreementManager I have 'private List<agreement> _Agreements'
A very simple structure but....
I was planning to remove a customer in CustomerForm.
The problem comes up when I want to remove a customer that has an agreement.
This must be inhibited(Show error/informative message and all that) if the customer is found as a customer in the agreementlist witch resides in the AgreementManager class.
How can I look in this list from 'inside' the Customer form.
I cant just make another agreementamng. object, because making a new one will not have the agreements in it.
How should/can I access methods in AgreementManager from CustomerForm?
Alternatively I could have a boolean _HasAgreement in the Customer objekt, to prevent delete. But that seems like a rather primitive solution now that i am learning to use obejct orientation and ObjectLists and working with managers.
thanks
BlindNavigator
|
|
|
|
|
You're mixing concerns here. Is it not the case that a Customer has a collection of Agreements? This would indicate that the customer object has a list associated with it - which simplifies what you need to do to check for customers.
|
|
|
|
|
My first ideas was:
agreementmanager would have a list of agreements. Agreement had a customer and a vehicle inside.
The Customermanager would have a CustomerList and methods to add/delete/edit etc. to this list.
and the Vehiclemanager would have a VehicleList and methods to add/delete/edit etc. to this list.
Considering your interesting suggestion, Pete.
Doing it this way I wonder if perhaps removing a Vehicle from a Vehicle List if that vehicle is in a agreementlist of a customer might become a similar problem instead.
It turned out a bit more tricky than i first imagined to 'separate concerns' here.
I was also toying with an idea of having a mainManager with all managers inside. Im not sure if that might solve the issues with removing enteties that are included in lists.
|
|
|
|
|
If I were designing a Form to be used for viewing the current state of a Customer, I would not have a method available from that form to actually delete a Customer ... for security reasons. I would allow only the Manager's Form to delete a Customer, or delete any agreement with the Customer.
I would probably want to show, on a given Customer's Form:
1. the customer information appropriate to the role of the person viewing the Form
2. at least the fact that the Customer has a current agreement(s).
3. depending on design: perhaps a mechanism to notify the Manager the customer has made a request to delete account/agreement.
I'd suggest (hard to be more specific without seeing/understanding your code):
1. when the current Customer Form is created, pass to it the necessary information it needs to present what you want to appear on the Form about the current agreement(s), or the fact there is no current agreement.
2. I'd use a separate Form to notify the Manager of a request for deleting an account, or agreement ... if the Customer Form did not allow such a notifiaction by the person using it.
«A man will be imprisoned in a room with a door that's unlocked and opens inwards ... as long as it does not occur to him to pull rather than push» Wittgenstein
|
|
|
|
|
Hi All,
We need to build our own workflow engine using c#,
please help me if you can how to start do that and let me know if it is possible or not.
Thanks
|
|
|
|
|
The first question I would have to ask is why? .NET has Workflow Foundation available for free, so have you looked into what it offers? As to the second part, yes it is possible to build your own Workflow engine using C#. Only you and your team can decide what you want it to be able to do, so it's up to you to define your requirements. For instance, what database do you intend to use to provide support for your Serializable Large Objects (SLOBs)?
|
|
|
|
|
|
What?
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
|