text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I have many hours thinking how i can solve , this is my funtion : This function split a string in parts of 36 characters then add the resultant characters with spaces for make a centered text : For example : Result : Line1 and Line2 are correct but i dont need the Line3 , how i can prevent to print this unnecessary line ? UPDATE : The lines are added into a ArrayList ( ) <code> private String TextAlignCenter ( String Line ) { String CenterLine = String.Empty ; if ( Line.Length > 36 ) { for ( int i = 0 ; i < Line.Length ; i += 36 ) { if ( ( i + 36 ) < Line.Length ) TextAlignCenter ( Line.Substring ( i , 36 ) ) ; else TextAlignCenter ( Line.Substring ( i ) ) ; } } else { Int32 CountLineSpaces = ( int ) ( 36 - Line.Length ) / 2 ; for ( int i = 0 ; i < CountLineSpaces ; i++ ) { CenterLine += ( Char ) 32 ; } CenterLine += Line ; } Console.WriteLine ( CenterLine ) ; return CenterLine ; } string x = `` 27 Calle , Col. Ciudad Nueva , San Pedro Sula , Cortes '' ; TextAlignCenter ( x ) ; Line1 : 27 Calle , Col. Ciudad Nueva , San PedLine2 : ro Sula , CortesLine3 : [ EmptyLine ] ArrayList Lines = new ArrayList ( ) ; string x = `` 27 Calle , Col. Ciudad Nueva , San Pedro Sula , Cortes '' ; Lines.Add ( TextAlignCenter ( x ) ) ; Console.WriteLine ( Lines.Count ) ; | Center and Split string with maxchar |
C_sharp : So Inversion Of Control is a vague description , so Dependency Injection became the new definition . This is a very , very powerful solution and is quite possibly just as confusing to someone whom has never encountered it.So in my quest to not be a deer in headlights , I read up . I found several terrific books and online post . But like all wonderful things , more questions arose rather then answers.The problem , absorbing variables from an unknown project to be implemented once they 've been introduced into my project.The solution : My injector : Then I created this : Then to implement it with a Shared Reference to be Fed Variables I created a class to be implemented like : Now the SiteParameters Class will be referenced by the other project ; which will allow me to actually call these properties whenever and wherever with : That was the implementation , but my question is this ... When do I do I use ? Constructor InjectionSetter InjectionInterface InjectionWhen would you use one or the other ? And for the task I mentioned should of I implemented such a difficult task to adjust for any changes made to the other project ? Did I fall off the curve in my thought process ? <code> public interface ISiteParameter { Guid CustomerId { get ; set ; } string FirstName { get ; set ; } string LastName { get ; set ; } string Phone { get ; set ; } } public interface IInjectSiteParameter { void InjectSite ( ISiteParameter dependant ) ; } public class SiteContent : IInjectSiteParameter { private ISiteParameter _dependent ; # region Interface Member : public void InjectSite ( ISiteParameter dependant ) { _dependant = dependant ; } # endregion } public class SiteParameters : ISiteParameter { public Guid Customer Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Phone { get ; set ; } } ISiteParameter i = new ISiteParameter ( ) ; MessageBox.Show ( i.Guid + i.FirstName + i.LastName + i.Phone ) ; | The Five W 's of DI , IoC because it is making my brain explode |
C_sharp : The following returns trueso doesThe RegEx is in SingleLine mode by default , so $ should not match \n . \n is not an allowed character.This is to match a single ASCII PascalCaseWord ( yes , it will match a trailing Cap ) Does n't work with any combinations of RegexOptions.Multiline | RegexOptions.SinglelineWhat am I doing wrong ? <code> Regex.IsMatch ( `` FooBar\n '' , `` ^ ( [ A-Z ] ( [ a-z ] [ A-Z ] ? ) + ) $ '' ) ; Regex.IsMatch ( `` FooBar\n '' , `` ^ [ A-Z ] ( [ a-z ] [ A-Z ] ? ) + $ '' ) ; | C # System.RegEx matches LF when it should not |
C_sharp : Really simple to replicate , the output is bizarre ; Expected output is `` bbb bbb '' Actual output is `` aaa bbb '' Has anyone got any MSDN explanation of this behaviour ? I could n't find any . <code> ( ( a ) new b ( ) ) .test ( ) ; new b ( ) .test ( ) ; public class a { public virtual void test ( string bob = `` aaa `` ) { throw new NotImplementedException ( ) ; } } public class b : a { public override void test ( string bob = `` bbb `` ) { HttpContext.Current.Response.Write ( bob ) ; } } | Overriding default parameters in C # |
C_sharp : I have the following scenario/requirement : I have two tasks , task A and task B , which both return the same type of data.If task A , upon completion , has data in its result , I need to return the result of Task A - otherwise I return the result of task B.I 'm trying to performance optimize this for parallellism and I 'm unsure if there 's a better way than what I 'm doing . This seems like a lot of code to do what I want . <code> var firstSuccessfulTask = await Task.WhenAny ( taskA , taskB ) ; if ( firstSuccessfulTask ! = taskA ) { await taskA ; } if ( taskA.Result ! = null ) { return taskA.Result ; } return await taskB ; | C # async/await - multiple tasks with one preferred |
C_sharp : I have a class that expects an IWorkspace to be created : and a derived class Derived . In this derived class I have a copy-constrcutor that should create an instance of Derived based on an instance of MyClass . The above won´t compile with following error : Can not access protected member MyClass.workspace ' via a qualifier of type 'MyClass ' ; the qualifier must be of type 'Derived ' ( or derived from it ) So what I´m trying to achieve is copying the base-class´ members to the derived one and create into a new instance of the latter . The reason why I do not use a constructor for IWorkspace within my derived class is that I do not have any access to such a workspace within the client-code , only to the instance of MyClass to be copied . <code> public class MyClass { protected IWorkspace workspace ; public MyClass ( IWorkspace w ) { this.workspace = w ; } } public class Derived : MyClass { public Derived ( MyClass m ) : base ( m.workspace ) { } } | Create a constructor that does not exist in base class |
C_sharp : In my program , I ran into a problem writing a small number to a context.Response that is then being read by a jQuery ajax response.returns [ object XMLDocument ] However , returns 0.00 as expected.Using `` n '' is perfectly fine for my program , but why did `` # . # '' return with an XMLDocument ? <code> value = -0.00000015928321772662457 ; context.Response.Write ( value.ToString ( `` # . # '' ) ) ; context.Response.Write ( value.ToString ( `` n '' ) ) ; | Why does n't # . # work for very small numbers ? |
C_sharp : I feel like I 'm stuck between several bad solutions here and need some advice on how to minimize future agony . We are using Massive ORM , which in its constructor has these lines : The important part for me here is that it reads the connection strings from ConfigurationManager . We are trying to centralize configuration , and in doing this we want to keep connection strings out of our web/app.configs ( we have somewhere around 150 deployed hosts , so the overhead is becoming significant ) . However , this breaks down since the config file read is hardcoded here , and the ConnectionStrings collection is read only ( there are workarounds , but they are all quite dirty ) . One possible way out of this is to extract these lines into a virtual method and then change it with inheritance . This is not so nice when we want to update Massive though , and also calling virtual methods from a constructor is potentially bad . What other alternatives do I have ? Main priority here is to minimize impact when updating . <code> var _providerName = `` System.Data.SqlClient '' ; if ( ConfigurationManager.ConnectionStrings [ connectionStringName ] .ProviderName ! = null ) _providerName = ConfigurationManager.ConnectionStrings [ connectionStringName ] .ProviderName ; _factory = DbProviderFactories.GetFactory ( _providerName ) ; ConnectionString = ConfigurationManager.ConnectionStrings [ connectionStringName ] .ConnectionString ; | Least-bad way to change constructor behaviour |
C_sharp : Is there any essential difference between this code : and this ? Or does the first invoke the method on the current thread while the second invokes it on a new thread ? <code> ThreadStart starter = new ThreadStart ( SomeMethod ) ; starter.Invoke ( ) ; ThreadStart starter = new ThreadStart ( SomeMethod ) ; Thread th = new Thread ( starter ) ; th.Start ( ) ; | .NET threading question |
C_sharp : I 've got an Application which consists of 2 parts at the momentA Viewer that receives data from a database using EFA Service that manipulates data from the database at runtime.The logic behind the scenes includes some projects such as repositories - data access is realized with a unit of work . The Viewer itself is a WPF-Form with an underlying ViewModel.The ViewModel contains an ObservableCollection which is the datasource of my Viewer.Now the question is - How am I able to retrieve the database-data every few minutes ? I 'm aware of the following two problems : It 's not the latest data my Repository is `` loading '' - does EF `` smart '' stuff and retrieves data from the local cache ? If so , how can I force EF to load the data from the database ? Re-Setting the whole ObservableCollection or adding / removing entities from another thread / backgroundworker ( with invokation ) is not possible . How am I supposed to solve this ? I will add some of my code if needed but at the moment I do n't think that this would help at all.Edit : This piece of code wo n't get the latest data - I edit some rows manually ( set IsResolved to true ) but this method retrieves it nevertheless.Edit2 : Edit3 : Final Question : The code above `` solves '' the problem - but in my opinion it 's not clean . Is there another way ? <code> public IEnumerable < Request > GetAllUnResolvedRequests ( ) { return AccessContext.Requests.Where ( o = > ! o.IsResolved ) ; } var requests = AccessContext.Requests.Where ( o = > o.Date > = fromDate & & o.Date < = toDate ) .ToList ( ) ; foreach ( var request in requests ) { AccessContext.Entry ( request ) .Reload ( ) ; } return requests ; | How to ... Display Data from Database |
C_sharp : doing a little experimenting to find out how things work . I have the following code ... I 'm wondering why MethodTest receives the int 20 almost always ( unless I 'm stepping through in debugger ) .Obviously there 's something missing in my understanding as I assumed that when ' i ' is passed it would be part of a managed thread 's local storage . <code> for ( int i = 0 ; i < 20 ; i++ ) { Task.Factory.StartNew ( ( ) = > MethodTest ( i ) ) ; } | Private variables in .net 4.0 tasks |
C_sharp : Update : check out the example at the bottomI need to message between classes . The publisher will loop indefinitely , call some method to get data , and then pass the result of that call into OnNext . There can be many subscribers , but there should only ever be one IObservable , and one long-running task . Here is an implementation.Output : Name : 1 Message : HiName : 2 Message : HiName : 3 Message : HiName : 1 Message : HiName : 2 Message : HiName : 3 Message : HiThis works fine . Notice that only one IObserver sends messages , but all subscriptions pick up the message . But , how do I separate the IObservable and the IObserver ? They are glued together as a Subject . Here is another approach.The problem here is that this creates two separate Tasks and two separate IObservers . Every subscription creates a new IObserver . You can confirm that because the Assert here fails . This does n't really make any sense to me . From what I understand of Reactive programming , I would n't expect the Subscribe method here to create a new IObserver each time . Check out this gist . It is a slight modification of the Observable.Create example . It shows how the Subscribe method causes an IObserver to be created each time it is called . How can I achieve the functionality from the first example without using a Subject ? Here is another approach that does not use Reactive UI at all ... You could create a Subject from the publisher if you want to , but it is not necessary.Lastly , I should add that ReactiveUI used to have a MessageBus class . I 'm not sure if it got removed or not , but it is no longer recommended . What do they suggest we use instead ? Working ExampleThis version is correct . I guess the only thing I 'm asking now is how do I do the equivalent of this with Observable.Create ? The problem with Observable.Create is that it runs the action for each subscription . That is not the intended functionality . The long running task here only runs once no matter how many subscriptions there are . <code> using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Diagnostics ; using System.Reactive.Linq ; using System.Reactive.Subjects ; using System.Threading.Tasks ; namespace UnitTestProject1 { [ TestClass ] public class UnitTest1 { private static string GetSomeData ( ) = > `` Hi '' ; [ TestMethod ] public async Task RunMessagingAsync ( ) { var subject = new Subject < string > ( ) ; //Create a class and inject the subject as IObserver new Publisher ( subject ) ; //Create a class and inject the subject as IObservable new Subscriber ( subject , 1.ToString ( ) ) ; new Subscriber ( subject , 2.ToString ( ) ) ; new Subscriber ( subject , 3.ToString ( ) ) ; //Run the loop for 3 seconds await Task.Delay ( 3000 ) ; } class Publisher { public Publisher ( IObserver < string > observer ) { Task.Run ( async ( ) = > { //Loop forever while ( true ) { //Get some data , publish it with OnNext and wait 500 milliseconds observer.OnNext ( GetSomeData ( ) ) ; await Task.Delay ( 500 ) ; } } ) ; } } class Subscriber { public string Name ; //Listen for OnNext and write to the debug window when it happens public Subscriber ( IObservable < string > observable , string name ) { Name = name ; var disposable = observable.Subscribe ( ( s ) = > Debug.WriteLine ( $ '' Name : { Name } Message : { s } '' ) ) ; } } } } [ TestMethod ] public async Task RunMessagingAsync2 ( ) { var observers = new List < IObserver < string > > ( ) ; var observable = Observable.Create ( ( IObserver < string > observer ) = > { observers.Add ( observer ) ; Task.Run ( async ( ) = > { while ( true ) { try { observer.OnNext ( GetSomeData ( ) ) ; } catch ( Exception ex ) { observer.OnError ( ex ) ; } await Task.Delay ( 500 ) ; } } ) ; return Disposable.Create ( ( ) = > { } ) ; } ) ; //Create a class and inject the subject as IObservable new Subscriber ( observable ) ; new Subscriber ( observable ) ; //Run the loop for 10 seconds await Task.Delay ( 10000 ) ; Assert.IsTrue ( ReferenceEquals ( observers [ 0 ] , observers [ 1 ] ) ) ; } using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Diagnostics ; using System.Threading.Tasks ; namespace UnitTestProject1 { [ TestClass ] public class UnitTest1 { private static string GetSomeData ( ) = > `` Hi '' ; class Publisher { public Publisher ( Action < string > onNext ) { Task.Run ( async ( ) = > { //Loop forever while ( true ) { //Get some data , publish it with OnNext and wait 500 milliseconds onNext ( GetSomeData ( ) ) ; await Task.Delay ( 500 ) ; } } ) ; } } class Subscriber { //Listen for OnNext and write to the debug window when it happens public void ReceiveMessage ( string message ) = > Debug.WriteLine ( message ) ; } [ TestMethod ] public async Task RunMessagingAsync ( ) { //Create a class and inject the subject as IObservable var subscriber = new Subscriber ( ) ; //Create a class and inject the subject as IObserver new Publisher ( subscriber.ReceiveMessage ) ; //Run the loop for 10 seconds await Task.Delay ( 10000 ) ; } } } using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Reactive.Disposables ; using System.Reactive.Linq ; using System.Threading ; using System.Threading.Tasks ; namespace UnitTestProject1 { class Subscriber { public string Name ; //Listen for OnNext and write to the debug window when it happens public Subscriber ( IObservable < string > observable , string name ) { Name = name ; var disposable = observable.Subscribe ( ( s ) = > Debug.WriteLine ( $ '' Name : { Name } Message : { s } '' ) ) ; } } internal class BasicObservable < T > : IObservable < T > { List < IObserver < T > > _observers = new List < IObserver < T > > ( ) ; public BasicObservable ( Func < T > getData , TimeSpan ? interval = null , CancellationToken cancellationToken = default ) = > Task.Run ( async ( ) = > { while ( ! cancellationToken.IsCancellationRequested ) { try { await Task.Delay ( interval ? ? new TimeSpan ( 0 , 0 , 1 ) ) ; var data = getData ( ) ; _observers.ForEach ( o = > o.OnNext ( data ) ) ; } catch ( Exception ex ) { _observers.ForEach ( o = > o.OnError ( ex ) ) ; } } _observers.ForEach ( o = > o.OnCompleted ( ) ) ; } , cancellationToken ) ; public IDisposable Subscribe ( IObserver < T > observer ) { _observers.Add ( observer ) ; return Disposable.Create ( observer , ( o ) = > _observers.Remove ( o ) ) ; } } public static class ObservableExtensions { public static IObservable < T > CreateObservable < T > ( this Func < T > getData , CancellationToken cancellationToken = default ) = > new BasicObservable < T > ( getData , default , cancellationToken ) ; public static IObservable < T > CreateObservable < T > ( this Func < T > getData , TimeSpan ? interval = null , CancellationToken cancellationToken = default ) = > new BasicObservable < T > ( getData , interval , cancellationToken ) ; } [ TestClass ] public class UnitTest1 { string GetData ( ) = > `` Hi '' ; [ TestMethod ] public async Task Messaging ( ) { var cancellationSource = new CancellationTokenSource ( ) ; var cancellationToken = cancellationSource.Token ; Func < string > getData = GetData ; var publisher = getData.CreateObservable ( cancellationToken ) ; new Subscriber ( publisher , `` One '' ) ; new Subscriber ( publisher , `` Two '' ) ; for ( var i = 0 ; true ; i++ ) { if ( i > = 5 ) { cancellationSource.Cancel ( ) ; } await Task.Delay ( 1000 ) ; } } } } | How to Separate IObservable and IObserver |
C_sharp : When you have some property that 's like : then compile and later change it to : it seems like the compiled code is different between the two assemblies , which I could see using the Reflector.Why does the compiler differentiates between the two code ? Is n't it only necessary to see if there is any ambiguous type at compile time and if there is n't , have the compiled code be the same for both ? I would assume the compiled code to use fully qualified names for every member at all times . <code> using Algebra ; public Algebra.Vector3 Direction { get { return this.direction ; } } using Algebra ; public Vector3 Direction { get { return this.direction ; } } | Why does the C # compiler differentiates between these 2 cases ? |
C_sharp : Straight to the point : I get a very related question which actually deals on why does i.ToString ( ) work fine.Edit : Just found out this corner case has been the most voted one in this SO thread ! <code> int ? i = null ; i.ToString ( ) ; //happyi.GetType ( ) ; //not happy | Why does some methods work while some do not on null values of nullable structs ? |
C_sharp : I wrote a tool that generates a C # source file containing the results of a processor intensive computation ( precomputing the result speeds up the startup time of my application by roughly 15 minutes ) . It is a byte [ ] that looks sorta like this : I 'm wondering though , are there hidden costs for hardcoding the result in code rather than writing it to a binary file ? Specifically , I fear C # may be storing two copies of the data in RAM ; one copy containing all the instructions/code to build precomputedData ( for reflection purposes ) and another copy containing the actual result of building precomputedData . Is this accurate ? Or is the choice between hardcoding it or storing it in a binary file , purely preference ? <code> public static byte [ ] precomputedData = new byte [ ] { 0x01,0x02,0x03,0x04,0x05,0x06,0x07 , 0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E , 0x0F,0x10 , ... . continue for 8000 more lines ... . | Are there hidden expenses hardcoding data as code in C # ? |
C_sharp : I need to calculate distances between every pair of points in an array and only want to do that once per pair . Is what I 've come up with efficient enough or is there a better way ? Here 's an example , along with a visual to explain what I 'm trying to obtain : e.g. , first get segments A-B , A-C , A-D ; then B-C , B-D ; and finally , C-D . In other words , we want A-B in our new array , but not B-A since it would be a duplication.Since this will be used with many thousands of points , I 'm thinking a precisely dimensioned array would be more efficient than using any sort of IEnumerable . <code> var pointsArray = new Point [ 4 ] ; pointsArray [ 0 ] = new Point ( 0 , 0 ) ; pointsArray [ 1 ] = new Point ( 10 , 0 ) ; pointsArray [ 2 ] = new Point ( 10 , 10 ) ; pointsArray [ 3 ] = new Point ( 0 , 10 ) ; // using ( n * ( n-1 ) ) / 2 to determine array sizeint distArraySize = ( pointsArray.Length* ( pointsArray.Length - 1 ) ) /2 ; var distanceArray = new double [ distArraySize ] ; int distanceArrayIndex = 0 ; // Loop through points and get distances , never using same point pair twicefor ( int currentPointIndex = 0 ; currentPointIndex < pointsArray.Length - 1 ; currentPointIndex++ ) { for ( int otherPointIndex = currentPointIndex + 1 ; otherPointIndex < pointsArray.Length ; otherPointIndex++ ) { double xDistance = pointsArray [ otherPointIndex ] .X - pointsArray [ currentPointIndex ] .X ; double yDistance = pointsArray [ otherPointIndex ] .Y - pointsArray [ currentPointIndex ] .Y ; double distance = Math.Sqrt ( Math.Pow ( xDistance , 2 ) + Math.Pow ( yDistance , 2 ) ) ; // Add distance to distanceArray distanceArray [ distanceArrayIndex ] = distance ; distanceArrayIndex++ ; } } | What is the most efficient way to avoid duplicate operations in a C # array ? |
C_sharp : Take the following code : The identifier foo has two types : IFoo - This is the type the compiler will enforce . I will only be able to call methods that are part of the IFoo contract , otherwise I 'll get a compiler error.FooImplementation - This is the type as known by the runtime . I can downcast foo to a FooImplementation at runtime , and then call non-IFoo methods of FooImplementation.My question : What is the proper terminology for these two types . I could swear in school we were taught that IFoo is the identifier 's static type and FooImplementation is its dynamic type , but after much searching on Google I ca n't seem to find any reference to this . <code> IFoo foo = new FooImplementation ( ) ; | What is the proper terminology for each type of an identifier ? |
C_sharp : I have a table that stores the history of changes on a product and want to get a list of records that have a change in Col1 or Col2 or Col3 but not show me records that do not have a change in any of these three columns .Here 's an example done in SQL . How do you do with Linq ? Create temporary table for testingInsert test dataSQL QueryDataResultHow do you do with Linq ? First approachThis is not very efficient . How I can do it without using a loop ? <code> CREATE TABLE # ProductHistorical ( IdProductHistorical int IDENTITY ( 1,1 ) NOT NULL , IdProduct int NOT NULL , DateChange datetime NULL , Col1 int NOT NULL , Col2 int NOT NULL , Col3 int NOT NULL , CONSTRAINT PK_ProductHistorical PRIMARY KEY CLUSTERED ( IdProductHistorical ASC ) ) GO INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13900000000 AS DateTime ) , 1 , 2 , 3 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13A00000000 AS DateTime ) , 1 , 2 , 3 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13B00000000 AS DateTime ) , 1 , 2 , 3 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13C00000000 AS DateTime ) , 1 , 1 , 3 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13D00000000 AS DateTime ) , 1 , 1 , 3 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13E00000000 AS DateTime ) , 2 , 2 , 2 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A13F00000000 AS DateTime ) , 2 , 2 , 2 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A14000000000 AS DateTime ) , 2 , 2 , 2 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 1 , CAST ( 0x0000A14100000000 AS DateTime ) , 1 , 2 , 3 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 2 , CAST ( 0x0000A14200000000 AS DateTime ) , 1 , 1 , 1 ) INSERT # ProductHistorical ( IdProduct , DateChange , Col1 , Col2 , Col3 ) VALUES ( 2 , CAST ( 0x0000A14300000000 AS DateTime ) , 1 , 1 , 2 ) SELECT phWithChanges.DateChange , phWithChanges.Col1 , phWithChanges.Col2 , phWithChanges.Col3 FROM # ProductHistorical ph CROSS APPLY ( SELECT TOP 1 * FROM # ProductHistorical phPost WHERE phPost.IdProduct=ph.IdProduct AND phPost.IdProductHistorical > ph.IdProductHistorical AND ( phPost.Col1 < > ph.Col1 OR phPost.Col2 < > ph.Col2 OR phPost.Col2 < > ph.Col2 ) ORDER BY phPost.IdProductHistorical ASC ) phWithChangesWHERE ph.IdProduct=1GROUP BY phWithChanges.DateChange , phWithChanges.Col1 , phWithChanges.Col2 , phWithChanges.Col3UNION -- Add First Row SELECT * FROM ( SELECT TOP 1 phFirst.DateChange , phFirst.Col1 , phFirst.Col2 , phFirst.Col3 FROM # ProductHistorical phFirst WHERE phFirst.IdProduct=1 ORDER BY phFirst.IdProductHistorical ) rowFirstORDER BY 1 IdProductHistorical IdProduct DateChange Col1 Col2 Col3 -- -- -- -- -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- -- -1 1 2013-01-01 00:00:00.000 1 2 32 1 2013-01-02 00:00:00.000 1 2 33 1 2013-01-03 00:00:00.000 1 2 34 1 2013-01-04 00:00:00.000 1 1 35 1 2013-01-05 00:00:00.000 1 1 36 1 2013-01-06 00:00:00.000 2 2 27 1 2013-01-07 00:00:00.000 2 2 28 1 2013-01-08 00:00:00.000 2 2 29 1 2013-01-09 00:00:00.000 1 2 310 2 2013-01-10 00:00:00.000 1 1 111 2 2013-01-11 00:00:00.000 1 1 2 DateChange Col1 Col2 Col3 -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- -- - -- -- -- -- -- -2013-01-01 00:00:00.000 1 2 32013-01-04 00:00:00.000 1 1 32013-01-06 00:00:00.000 2 2 22013-01-09 00:00:00.000 1 2 3 var query= ( from ph in ProductHistorical.Where ( p= > p.IdProduct==1 ) orderby ph.DateChange ascending select new ProductHistoricalItem { DateChange = ph.DataChange , Col1 = ph.Col1 , Col2 = ph.Col2 , Col3 = ph.Col3 } ) ; List < ProductHistoricalItem > listResult=new List < ProductHistoricalItem > ( ) ; ProductHistoricalItem previous = null ; foreach ( ProductHistoricalItem item in query ) { if ( previous == null || previous.Col1 ! = item.Col1 || previous.Col2 ! = item.Col2 || previous.Col3 ! = item.Col3 ) { listResult.Add ( item ) ; previous = item ; } } | Linq Filter row differences in historical |
C_sharp : We know that these two addition statements are equivalent and compile to the same IL code : However , when there is an explicit cast required I have noticed something strange : It is obvious why the second statement requires an explicit cast because the result of the addition is an integer . But the weird thing to me is the first statement . It compiles to the exact same IL as the third statement , so it looks like compiler adds a cast that is supposed to be explicit , for us . But it ca n't do it in the second statement.It seems contradictory to me because I would expect the first statement to be equivalent to the second and never compile , so why does it compile ? Note : This does n't compile when an explicit cast is required from long to int : <code> int x = 100 ; x += 100 ; x = x + 100 ; byte b = 100 ; b += 200 ; // Compiles ( 1 ) b = b + 200 ; // Can not implicitly convert int to byte ( 2 ) b = ( byte ) ( b + 200 ) ; // Compiles ( 3 ) int x = 100 ; long y = 200 ; x += y ; | Why is x = x + 100 treated differently than x += 100 that compiles to the same IL ? |
C_sharp : I have a bit of a hard time putting this just in words , so I 'll use some code to help explain myself and my problem.So imagine I have two classes ClassA and ClassB : as you can see ClassB contains ClassA , but I have another class for it ClassAOwned because I want ClassB to own ClassA ( flatten its columns into ClassB table ) , but also have ClassA DbSet as a seperate table ( and as I understand entity class can not be owned and have its own DbSet at the same time ) , so I had to use 2 different classes . Here 's my context to make it easier to understand : Now my problem comes when I 'm trying to insert ClassA and ClassB to context at the same time and have to match their ClassAId values which is generated by database provider : when using InMemoryDatabase the following call : actually changes classA.ClassAId to correct generated value , however when using SQL server classA.ClassAId gets set to int.MinValue so next call : sets classB.ClassA.ClassAId to int.MinValue . and the final call : changes classA.ClassAId to correct generated value , but classB.ClassA.ClassAId stays as int.MinValue and that 's the value that gets inserted into the database . My question is : Is there a way to tell EF core that when adding two entities into context set one 's property to whatever value was generated for another entity 's primary key ? So the functionality I 'm looking for is exactly the same as adding two entities where one has a foreign key , except in this case it 's not really a foreign key.A simple workaround would be to set the `` foreign key '' ( classB.ClassA.ClassAId ) after testContext.SaveChanges ( ) and save changes again , but then it becomes two separate operations and what if the second one fails ? The database will be in invalid state . <code> class ClassA { public int ClassAId { get ; set ; } public string Name { get ; set ; } } [ Owned ] class ClassAOwned { public int ClassAId { get ; set ; } public string Name { get ; set ; } } class ClassB { public int ClassBId { get ; set ; } public string Action { get ; set ; } public ClassAOwned ClassA { get ; set ; } } class TestContext : DbContext { public DbSet < ClassA > ClassAs { get ; set ; } public DbSet < ClassB > ClassBs { get ; set ; } protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder ) { optionsBuilder.UseInMemoryDatabase ( `` TestContext '' ) ; } } var testContext = new TestContext ( ) ; var classA = new ClassA { Name = `` classAName '' } ; var classB = new ClassB { Action = `` create '' , ClassA = new ClassAOwned { ClassAId = classA.ClassAId , Name = classA.Name } } ; testContext.ClassAs.Add ( classA ) ; testContext.ClassBs.Add ( classB ) ; classB.ClassA.ClassAId = classA.ClassAId ; testContext.SaveChanges ( ) ; testContext.ClassAs.Add ( classA ) ; classB.ClassA.ClassAId = classA.ClassAId ; testContext.SaveChanges ( ) ; | How to set class property 's value to be set to generated id value of another class on insertion to database ? |
C_sharp : Q1 Why do new classes from .NET implement interfaces only partially ? Q2 Shall I do the same in my code ? I asked this question here , so I thought , okay that was long time ago , you can have different usage etc etc , and now such implementation is supported only for consistency reasons . But new classes also do that.OldNewUPDATEI am not worried why I get exceptions , it is clear . But I do n't understand why classes implement the well defined contract , but not all the members ( which can lead to unpleasant run time exceptions ) ? <code> int [ ] list = new int [ ] { } ; IList iList = ( IList ) list ; ilist.Add ( 1 ) ; //exception here ICollection c = new ConcurrentQueue < int > ( ) ; var root = c.SyncRoot ; //exception here | Why do core types implement interfaces only partly ? |
C_sharp : The given codeemits the following warning : If I remove .Select ( ) clause it disappears.But it 's not clear to me what exactly I need to .Ensure so that the cccheck was satisfied . <code> static public int Q ( ) { return Enumerable.Range ( 0 , 100 ) .Select ( i = > i ) .First ( ) ; } warning : CodeContracts : requires unproven : Any ( source ) | Contract that ensures the IEnumerable is not empty |
C_sharp : I have a theorical/pratical question about how inheritance works in C # .Let 's say that I have to model some autos , so I have a few common methods that all the autos must implement and a pilot should know . In code-words this should be an Interface : Now , all kind of car should have some common technical implementations beside the actions that a pilot can perform over them , let 's say the property fuelLevel , at this point I still do n't want to know how a car speeds up or breaks down , so I would wrote : Now I want to model a Ferrari , so : Now , in Java this code should work ( changing some syntax ) , but in C # wo n't because it says : Why ? How should I fix this problem ? <code> interface Automobile { void speedup ( ) ; void break ( ) ; void steer ( ) ; //bla bla } abstract class Car : Automobile { int fuelLevel ; // for example ... . public abstract void speedup ( ) ; public abstract void break ( ) ; public abstract void steer ( ) ; } class Ferrari : Car { public void speedup ( ) { ... } public void break ( ) { ... } public void steer ( ) { ... } } Error 1 'Ferrari ' does not implement inherited abstract member 'Car.speedup ( ) 'Error 1 'Ferrari ' does not implement inherited abstract member 'Car.break ( ) 'Error 1 'Ferrari ' does not implement inherited abstract member 'Car.steer ( ) ' | About C # and Inheritance |
C_sharp : I could n't find any information on this through professor Google , so here I am . Take the given path name and paste it into Windows Explorer . I stumbled across this after discovering bug in my code that generated the paths with an extra ' . ' in the path name before a directory \ separator ... In code , .NET will accept the path when calling File.Create and a file will be generated , but at this path : Copying C : \\pathto.\file.ext into Windows Explorer 's address bar and watch the ' . ' disappear and take you to C : \\pathto\file.extIs it normal behavior for .NET and Windows to It 's not causing an issue because the ' . ' is being removed by both .NET and Windows when passed into file operations . The real issue is that all the files in the DB have filenames with a '.\ ' , but exists in paths that do not have a '.\ ' ... and File.Exists ( ) works too , although the path is not the 'real ' physical location ... What 's going on here ? <code> @ '' C : \\pathto.\file.ext '' @ '' C : \\pathto\file.ext '' | Strange behavior from .NET regarding file paths |
C_sharp : I am trying to read the System Event Logs in C # .NET 3.5 with the following method EventLog.GetEventLogs . This seems to be working perfectly for all kinds of Event Logs that I want to take a look at . There is but one exception : Microsoft-Windows-Kernel-Power Event Logs which can be read but produces the following Message : Microsoft-Windows-Kernel-Power The description for Event ID ' X ' in Source 'Microsoft-Windows-Kernel-Power ' can not be found . The local computer may not have the necessary registry information or message DLL files to display the message , or you may not have permission to access them . The following information is part of the event : ' Y ' , ' Z'instead of the correct Message displayed in the Windows Event Viewer.Code looks like thisThis is happening even if I run the application as administrator . I am at a loss here . I have searched far and wide all over the internet and found a couple posts that seem to have similar issues but most are for writing Event Logs instead of having problems reading them . Is anyone familiar with that kind of problem or can point me in the right direction ? All my registry keys etc seem to be set up correctly ( and it is also showing the same results on a different PC ) .EDIT : Windows Version 10.0.18363 Build 18363 but it is happening on multiple PCs ( I am not sure what Windows version the others are using ) . In fact , I have not found a single one which is working ( tested 5 so far ) . <code> var myEventLogs = new List < myModels.EventLogEntry > ( ) ; foreach ( var eventLog in EventLog.GetEventLogs ( ) ) { foreach ( var entry in eventLog.Entries ) { if ( entry.Source.IndexOf ( `` kernel-power '' , StringComparison.OrdinalIgnoreCase ) == -1 & & entry.Message.IndexOf ( `` kernel-power '' , StringComparison.OrdinalIgnoreCase ) == -1 ) continue ; myEventLogs.Add ( new myModels.EventLogEntry ( entry.Source , entry.Message ) ) } } | The description for Event ID ' X ' in Source 'Microsoft-Windows-Kernel-Power ' can not be found |
C_sharp : I 'm facing a general question where I ca n't find a good example to try-it-for-myself . Google is n't a help neither.Imagine a structure like this : What if the server is slow and takes a while to accept the mail . Is it possible that the SmtpClient is disposed before the operation is done ? Will it be canceled or broken in any way ? Is there a general answer for this ? The servers in here are too fast , do n't know how to do a try-out.If thinking about canceling a BackgroundWorker it 's always finishing the current operation . Could be the same here , or maybe not ... <code> MailMessage mail = new MailMessage ( sender , receiver ) ; using ( SmtpClient client = new SmtpClient ( ) ) { client.Host ... client.Port ... mail.subject ... mail.body ... client.SendAsync ( mail ) ; } | Using-statement with async call | Cancel operation ? |
C_sharp : I have an array of Vehicles in C # and some vehicles are Cars and others are SUVs . I am wondering what is the best way to fetch car with lowest weight . If no car is found in the array then find SUV with lowest weight.Below is code segment I have using LINQ . I am wondering if there is better way to fetch this using one query instead of two queries.Is there a better way to accomplish the same using groupby or some other LINQ trick ? <code> Vehicle listVehicles [ ] = ... Vehicle lightestVehicle = ( from aVehicle in listVehicles where aVehicle.Type == CAR orderby aVehicle.Weight ascending ) ? .FirstOrDefault ( ) ; if ( null == lightestVehicle ) lightestVehicle = ( from aVehicle in listVehicles where aVehicle.Type == SUV orderby aVehicle.Weight ascending ) ? .FirstOrDefault ( ) ; return lightestVehicle ; | Selecting first element of a group from LINQ search results |
C_sharp : Most , if not all , examples of Dapper in .NET I 've seen use a structure like this : If you have a Web API , is it wise to make a new connection every time a request is made to the server ? Or would it be a better pattern to abstract the connection into another class and inject it into each controller so they are using the same connection.On the surface , it seems like reusing the connection would result in quicker responses but I do n't know the nitty gritty of what 's going on in a SqlConnection object so I 'm not sure if it 's a good idea . <code> using ( SqlConnection conn = new SqlConnection ( ConnectionString ) ) { conn.Open ( ) ; return conn.Query < T > ( sql , param ) ; } | Reusing database connection with Dapper in .NET Web API |
C_sharp : Suppose you have 2 classes like so : Now imagine you have an instance of each class and you want to copy the values from a into b . Is there something like MemberwiseClone that would copy the values where the property names match ( and of course is fault tolerant -- one has a get , and the other a set , etc . ) ? Something like this is pretty easy in a language like JavaScript.I 'm guessing the answer is no , but maybe there is a simple alternative too . I have written a reflection library to do this , but if built in to C # /.NET at a lower level would probably be more efficient ( and why re-invent the wheel ) . <code> public class ClassA { public int X { get ; set ; } public int Y { get ; set ; } public int Other { get ; set ; } } public class ClassB { public int X { get ; set ; } public int Y { get ; set ; } public int Nope { get ; set ; } } var a = new ClassA ( ) ; var b = new classB ( ) ; a.CopyTo ( b ) ; // ? ? | Is there anything built into .NET/C # for copying values between objects ? |
C_sharp : I have an interface IKey which I want to have a method which will return the key as a string . We looked at having a method like this : which would return the string representation , but would have liked to be able to declare ToString ( ) again in the interface to force implementers to implement it , but it does n't force them to as they have an implementation inherited from Object . This was suggested : this forces an implementation of the method in any implementing class , but due to the way that optional parameters work callers do not need to provide a value for this , and you ensure that any calls to the ToString ( ) method on objects which are either cast as the interface IKey or the implementing class will always call the class implementation and not the Object implementation.In the implementations we can just ignore the dummyParameter and return what we want , safe in the knowledge that calling ToString ( ) will always actually call ToString ( null ) .Now this feels wrong all over to me , but at the same time it does have something quite nice about it . It is almost exactly the same as having a method GetAsString ( ) as this could only be called on the IKey interface and derived classes except that it looks like the more natural ToString ( ) method that we want to use and that we are able to force the implementing of in the child class.Having said that the dummy parameter which is not used feels wrong.So is this horrendous ? Or great ? And is this question appropriate for SO or should it be on Programmers ? Examplesoutput : <code> String GetAsString ( ) ; public interface IKey { string ToString ( string dummyParameter=null ) ; } public class Key : IKey { public string ToString ( string abc = null ) { return `` 100 '' ; } } Key key = new Key ( ) ; Trace.WriteLine ( key.ToString ( ) ) ; Trace.WriteLine ( key.ToString ( null ) ) ; Trace.WriteLine ( key.ToString ( `` ac '' ) ) ; Trace.WriteLine ( ( ( object ) key ) .ToString ( ) ) ; 100100100Blah.Tests.Key | Is taking advantage of optional parameter edge cases to force implementations of ToString via an interface abuse of the language ? |
C_sharp : i have this classand i have a manager that gets several lists of ConnectionResult and count each value greater then a specific number determined by configuration . my implementation is so : but i want to make it better , so i started to write it in linq and i got tobut this gives me an error of Can not implicitly convert type 'int ' to 'bool'.is there a way to count it in linq or do i have to stay with what i wrote ? btw , i 'm new to linq <code> public class ConnectionResult { private int connectionPercentage ; public int ConnectPercentage { get { return connectionPercentage ; } } public ConnectionResult ( int ip ) { // Check connection and set connectionPercentage } } public class CurrentConnections { private static CurrentConnections inst ; private CurrentConnections ( ) { } public static CurrentConnections GetInstance { get { if ( inst ! = null ) { inst = new CurrentConnections ( ) ; } return inst ; } } public int CountActiveConnections ( params List < ConnectionResult > [ ] conns ) { int rtVal = 0 ; foreach ( List < ConnectionResult > connectionResult in conns ) { foreach ( var currConn in connectionResult ) { if ( currConn.ConnectPercentage > ACCEPTABLE_CONNECTION ) { rtVal++ ; } } } return rtVal ; } } conns.Count ( x = > x.Count ( y = > y.ConnectPercentage > ACCEPTABLE_CONNECTION ) ) ; | Need better way to sum up data |
C_sharp : For example , if I had two lists , I 'd do : Or if I had three , I 'd dobut if I do n't know at compile time how many lists are in the lists collection , how can I easily iterate over every permutation ? A C # solution is ideal , but a solution in any language that demonstrates a suitable algorithm would be handy.A good 2-dimensional example would be a list of columns and a list of rows on a spreadsheet , where I need to do processing on each cell . It 's an n-dimensional problem , however . <code> foreach ( Item item1 in lists [ 0 ] ) foreach ( Item item2 in lists [ 1 ] ) // Do something with item1 and item2 foreach ( Item item1 in lists [ 0 ] ) foreach ( Item item2 in lists [ 1 ] ) foreach ( Item item3 in lists [ 2 ] ) // Do something with item1 , item2 , and item3 | How do you iterate over an arbitrary number of lists , including every permutation ? |
C_sharp : Hello everyone : ) Here 's the situation : I have a baddy prefab which has two collider components : a simple CapsuleCollider2D used for physics , and a trigger PolygonCollider2D used only for mouse point collisions.The PolygonCollider2D is updated through an attached script ( Baddy.cs ) only when needed using : Yes , this is poor practice , but it get 's the job done . It works perfectly : in the scene view of the game I can pause and see that there is indeed a polygon collider on our baddy prefab.In another attached script ( CollisionHandler.cs ) we check for a mouse press on our baddy : However hit.collider==this.gameObject.GetComponent < PolygonCollider2D > ( ) turns out false , even though I could print both hit.collider and this.gameObject.GetComponent < PolygonCollider2D > ( ) immediately before hand in our if ( MousePress ( ) ) and have them both defined as : They could n't be different PolygonColliders because there can only be one at a time , since our Baddy script removes and creates the PolygonCollider simultaneously.Any ideas what could be going wrong ? <code> if ( this.gameObject.GetComponent < PolygonCollider2D > ( ) ! =null ) { Destroy ( this.gameObject.GetComponent < PolygonCollider2D > ( ) ) ; } this.gameObject.AddComponent < PolygonCollider2D > ( ) ; this.gameObject.GetComponent < PolygonCollider2D > ( ) .isTrigger=true ; if ( MousePress ( ) ) { hit=Physics2D.Raycast ( level.mousePoint , Vector2.zero , 0f ) ; if ( hit & & hit.collider==this.gameObject.GetComponent < PolygonCollider2D > ( ) ) { print ( `` baddy mousePress '' ) ; } } D_Prefab ( Clone ) ( UnityEngine.PolygonCollider2D ) | Prefab Collider2D not Recognized as Raycast Collider |
C_sharp : Consider this code : In above code s is string but b is false.actually s as string , Why i get this result ? Why compiler has this behavior ? <code> class Program { static void Main ( string [ ] args ) { string s = null ; bool b = s is string ; Console.WriteLine ( b ) ; } } | Why null string is not a string object |
C_sharp : I 'm wondering if there is a better way to approach this problem . The objective is to reuse code.Let ’ s say that I have a Linq-To-SQL datacontext and I 've written a `` repository style '' class that wraps up a lot of the methods I need and exposes IQueryables . ( so far , no problem ) .Now , I 'm building a service layer to sit on top of this repository , many of the service methods will be 1 < - > 1 with repository methods , but some will not . I think a code sample will illustrate this better than words.This particular case is not the best illustration , since I could just call the repository directly in the GetActiveMyClass method , but let ’ s presume that my private IQueryable does some extra processing and business logic that I do n't want to replicate in both of my public methods . Is that a bad way to attack an issue like this ? I do n't see it being so complex that it really warrants building a third class to sit between the repository and the service class , but I 'd like to get your thoughts.For the sake of argument , lets presume two additional things.This service is going to be exposed through WCF and that each of these public IEnumerable methods will be calling a .Select ( m = > m.ToViewModel ( ) ) on each returned collection which will convert it to a POCO for serialization.The service will eventually need to expose some context.SomeOtherTable which wont be wrapped into the repository . <code> public class ServiceLayer { MyClassDataContext context ; IMyRepository rpo ; public ServiceLayer ( MyClassDataContext ctx ) { context = ctx ; rpo = new MyRepository ( context ) ; } private IQueryable < MyClass > ReadAllMyClass ( ) { // pretend there is some complex business logic here // and maybe some filtering of the current users access to `` all '' // that I do n't want to repeat in all of the public methods that access // MyClass objects . return rpo.ReadAllMyClass ( ) ; } public IEnumerable < MyClass > GetAllMyClass ( ) { // call private IQueryable so we can do attional `` in-database '' processing return this.ReadAllMyClass ( ) ; } public IEnumerable < MyClass > GetActiveMyClass ( ) { // call private IQueryable so we can do attional `` in-database '' processing // in this case a .Where ( ) clause return this.ReadAllMyClass ( ) .Where ( mc = > mc.IsActive.Equals ( true ) ) ; } # region `` Something my class MAY need to do in the future '' private IQueryable < MyOtherTable > ReadAllMyOtherTable ( ) { // there could be additional constrains which define // `` all '' for the current user return context.MyOtherTable ; } public IEnumerable < MyOtherTable > GetAllMyOtherTable ( ) { return this.ReadAllMyOtherTable ( ) ; } public IEnumerable < MyOtherTable > GetInactiveOtherTable ( ) { return this.ReadAllMyOtherTable.Where ( ot = > ot.IsActive.Equals ( false ) ) ; } # endregion } | Is there anything wrong with having a few private methods exposing IQueryable < T > and all public methods exposing IEnumerable < T > ? |
C_sharp : I have an Item class . I have around 10-20 derivatives of it each containing different types of data . Now when it comes to rendering different types of Item , I 'm forced to use likes of : Unfortunately @ Html.DisplayFor ( ) does not work in this case because the Model is type of Item , DisplayTemplates\Item.cshtml is displayed.HTML helpers do n't help either because of the same `` if/is '' chain.I could incorporate rendering logic inside the classes themselves , and call @ Model.Render ( ) but they belong to business logic , not presentation . It would be a sin.There is only one option of @ Html.Partial ( Model.GetType ( ) .Name ) but it feels wrong . You expect a solution without meta-magic . Is there a better way ? <code> < div > @ if ( Model is XItem ) { ... rendering logic 1 ... } @ if ( Model is YItem ) { ... rendering logic 2 ... } @ if ( Model is ZItem ) { ... rendering logic 3 ... } ... goes on and on forever ... < /div > | How to render derived types of a class differently ? |
C_sharp : So I have an integer , e.g . 1234567890 , and a given set of numbers , e.g . { 4 , 7 , 18 , 32 , 57 , 68 } The question is whether 1234567890 can be made up from the numbers given ( you can use a number more than once , and you do n't have to use all of them ) . In the case above , one solution is:38580246 * 32 + 1 * 18 ( Does n't need to give specific solution , only if it can be done ) My idea would be to try all solutions . For example I would try1 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 42 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 83 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 12 ... ..308 641 972 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 1234567888308 641 973 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 1234567892 == > exceeds0 * 4 * + 1 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 71 * 4 * + 1 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 112 * 4 * + 1 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 15and so on ... Here is my code in c # : The code works fine ( as far as I know ) but is way too slow . It takes about 3 secs to solve the example , and there may be 10000 numbers to make from 100 numbers . <code> static int toCreate = 1234567890 ; static int [ ] numbers = new int [ 6 ] { 4 , 7 , 18 , 32 , 57 , 68 } ; static int [ ] multiplier ; static bool createable = false ; static void Main ( string [ ] args ) { multiplier = new int [ numbers.Length ] ; for ( int i = 0 ; i < multiplier.Length ; i++ ) multiplier [ i ] = 0 ; if ( Solve ( ) ) { Console.WriteLine ( 1 ) ; } else { Console.WriteLine ( 0 ) ; } } static bool Solve ( ) { int lastIndex = 0 ; while ( true ) { int comp = compare ( multiplier ) ; if ( comp == 0 ) { return true ; } else if ( comp < 0 ) { lastIndex = 0 ; multiplier [ multiplier.Length - 1 ] ++ ; } else { lastIndex++ ; for ( int i = 0 ; i < lastIndex ; i++ ) { multiplier [ multiplier.Length - 1 - i ] = 0 ; } if ( lastIndex > = multiplier.Length ) { return false ; } multiplier [ multiplier.Length - 1 - lastIndex ] ++ ; } } } static int compare ( int [ ] multi ) { int osszeg = 0 ; for ( int i = 0 ; i < multi.Length ; i++ ) { osszeg += multi [ i ] * numbers [ i ] ; } if ( osszeg == toCreate ) { return 0 ; } else if ( osszeg < toCreate ) { return -1 ; } else { return 1 ; } } | How can I determine if a certain number can be made up from a set of numbers ? |
C_sharp : Say I have an array that is stored in 0° rotation : And I want it returned in a good approximation if I pass , for example 30° as parameter , it would be something like:45° would beI am aware of the solutions posted for 90° rotations . But I do n't think that will help me here ? I do n't have any examplecode because I currently would n't even know where to start looking . If there are any keywords I can google that point me in the directions of some formula I can adapt for this , that would also be great.Spectre 's code solution in C # : test : <code> 0 0 1 0 00 0 1 0 0 1 1 1 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 01 1 0 1 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 10 1 0 1 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 class Rotation { public Rotation ( ) { A = new int [ xs , ys ] { { 0,0,0,9,0,0,0 } , { 0,0,0,9,0,0,0 } , { 0,0,0,9,0,0,0 } , { 9,9,9,9,0,0,0 } , { 0,0,0,0,0,0,0 } , { 0,0,0,0,0,0,0 } , { 0,0,0,0,0,0,0 } , } ; B = new int [ xs , ys ] ; deg = ( float ) ( Math.PI / 180.0 ) ; } public const int xs = 7 ; // matrix size public const int ys = 7 ; const int x0 = 3 ; // rotation center cell const int y0 = 3 ; readonly float deg ; public int [ , ] A ; public int [ , ] B ; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - public void rotcv ( float ang ) { rotcw ( Rotation.x0 , Rotation.y0 , ang ) ; } private void rotcw ( int x0 , int y0 , float ang ) // rotate A - > B by angle ang around ( x0 , y0 ) CW if ang > 0 { int x , y , ix0 , iy0 , ix1 , iy1 , q ; double xx , yy , fx , fy , c , s ; // circle kernel c = Math.Cos ( -ang ) ; s = Math.Sin ( -ang ) ; // rotate for ( y = 0 ; y < ys ; y++ ) for ( x = 0 ; x < xs ; x++ ) { // offset so ( 0,0 ) is center of rotation xx = x - x0 ; yy = y - y0 ; // rotate ( fx , fy ) by ang fx = ( ( xx * c ) - ( yy * s ) ) ; fy = ( ( xx * s ) + ( yy * c ) ) ; // offset back and convert to ints and weights fx += x0 ; ix0 = ( int ) Math.Floor ( fx ) ; fx -= ix0 ; ix1 = ix0 + 1 ; if ( ix1 > = xs ) ix1 = ix0 ; fy += y0 ; iy0 = ( int ) Math.Floor ( fy ) ; fy -= iy0 ; iy1 = iy0 + 1 ; if ( iy1 > = ys ) iy1 = iy0 ; // bilinear interpolation A [ fx ] [ fy ] - > B [ x ] [ y ] if ( ( ix0 > = 0 ) & & ( ix0 < xs ) & & ( iy0 > = 0 ) & & ( iy0 < ys ) ) { xx = ( A [ ix0 , iy0 ] ) + ( ( A [ ix1 , iy0 ] - A [ ix0 , iy0 ] ) * fx ) ; yy = ( A [ ix0 , iy0 ] ) + ( ( A [ ix1 , iy0 ] - A [ ix0 , iy0 ] ) * fx ) ; xx = xx + ( ( yy - xx ) * fy ) ; q = ( int ) xx ; } else q = 0 ; B [ x , y ] = q ; } } } static void Main ( string [ ] args ) { Rotation rot = new Rotation ( ) ; for ( int x = 0 ; x < Rotation.xs ; x++ ) { for ( int y = 0 ; y < Rotation.xs ; y++ ) { Console.Write ( rot.A [ x , y ] + `` `` ) ; } Console.WriteLine ( ) ; } Console.WriteLine ( ) ; float rotAngle = 0 ; while ( true ) { rotAngle += ( float ) ( Math.PI/180f ) *90 ; rot.rotcv ( rotAngle ) ; for ( int x = 0 ; x < Rotation.xs ; x++ ) { for ( int y = 0 ; y < Rotation.xs ; y++ ) { Console.Write ( rot.B [ x , y ] + `` `` ) ; } Console.WriteLine ( ) ; } Console.WriteLine ( ) ; Console.ReadLine ( ) ; } } | How can I rotate a 2d array by LESS than 90° , to the best approximation ? |
C_sharp : When I run this query in linqpad : It returns a record that matches.When I try running the same query in visual studio it does not return any matching records . This is the code I am using : Can anyone see why this it works in linqpad but does not work in visual studio ? <code> Customer.Where ( c = > ( c.CustomerName == `` test '' ) ) List < Customer > customerList = new List < Customer > ( ) ; using ( DBEntities db = new DBEntities ( ) ) { try { customerList = db.Customer.Where ( c = > ( c.customerName == `` test '' ) ) .ToList ( ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.ToString ( ) ) ; } } return customerList ; | linq query for varchar field not returning any results |
C_sharp : The following snippet is taken from an example of ComboBox : :DrawItem implementation on this MSDN page : I question this part : new SolidBrush ( animalColor ) Since this is neither deliberately given a Dispose nor is it wrapped in a using , I assume this is also an example of poor form , since the SolidBrush object will be created and never disposed.I have always labored under the assumption that I must use one of the aforementioned disposal mechanisms directly , or risk a memory leak.Am I correct , or is there some deeper implicit disposal going on of which I am unaware ? Perhaps because it was never assigned to a variable ? <code> e.Graphics.FillRectangle ( new SolidBrush ( animalColor ) , rectangle ) ; | Is an object creating using an `` inline '' new statement automatically disposed ? |
C_sharp : Imagine that I have a visits index that contains documents of type 'visit ' that look like the following : The following function will return a histogram which returns buckets of visits for each day in the given range according to the given time zone.Now imagine that I changed things up a bit . Imagine that I added a new field to the document : And assume that I want to return the following : because the visit spanned two days and I want a date histogram which records one unit for each day that a visit spans.How would I do this with NEST/Elastic Search ? Note 1 : Unless someone convinces me otherwise , I do n't think would be a good idea to collect all documents in the range and perform the aggregation/bucketization and date histogram in the middle-tier ( or C # layer ) .Note 2 : The time zone aspect of this problem is critical because I need the counts to be bucketized according to the given time zone . <code> { `` id '' : `` c223a991-b4e7-4333-ba45-a576010b568b '' , // other properties `` buildingId '' : `` 48da1a81-fa73-4d4f-aa22-a5750162ed1e '' , `` arrivalDateTimeUtc '' : `` 2015-12-22T21:15:00Z '' } public Bucket < HistogramItem > Execute ( MyParameterType parameters ) { var buildingFilter = Filter < VisitProjection > .Term ( x = > x.BuildingId , parameters.BuildingId ) ; var dateFilter = Filter < VisitProjection > .Range ( r = > r .OnField ( p = > p.ArrivalDateTimeUtc ) .GreaterOrEquals ( parameters.EarliestArrivalDateTimeUtc ) .LowerOrEquals ( parameters.LatestArrivalDateTimeUtc ) ) ; var result = _elasticClient.Search < VisitProjection > ( s = > s .Index ( `` visits '' ) .Type ( `` visit '' ) .Aggregations ( a = > a .Filter ( `` my_filter_agg '' , f = > f .Filter ( fd = > buildingFilter & & dateFilter ) .Aggregations ( ta = > ta.DateHistogram ( `` my_date_histogram '' , h = > h .Field ( p = > p.ArrivalDateTimeUtc ) .Interval ( parameters.DateInterval ) // `` day '' .TimeZone ( NodaTimeHelpers.WindowsToIana ( parameters.TimeZoneInfo ) ) // This is a critical piece of the equation . .MinimumDocumentCount ( 0 ) ) ) ) ) ) ; return result.Aggs.Nested ( `` my_filter_agg '' ) .DateHistogram ( `` my_date_histogram '' ) ; } } // Returns [ { Date : 12/22/2015 12:00:00 AM , DocCount : 1 } ] { `` id '' : `` c223a991-b4e7-4333-ba45-a576010b568b '' , // other properties `` buildingId '' : `` 48da1a81-fa73-4d4f-aa22-a5750162ed1e '' , `` arrivalDateTimeUtc '' : `` 2015-12-22T21:15:00Z '' , `` departureDateTimeUtc '' : `` 2015-12-23T22:00:00Z '' // new property } // Returns [ { Date : 12/22/2015 12:00:00 AM , DocCount : 1 } , { Date : 12/23/2015 12:00:00 AM , DocCount : 1 } ] | How can I reshape my data before I turn it into a histogram ? |
C_sharp : I 'm working on a rehosted workflow designer using WF 4 , my application which uses this designer control is a multi-language application that loads 2 or more language specific resource dlls . if I have two satellite assemblies for one language such as `` en '' and `` en-US '' , designer throws an exception like this : and here is the stack trace : It 's worthy to mention that when I took a look at my satellite assemblies ' properties , Details tab , I realized that they are all Neutral Language . I think they must be Specific Language so the application can recognize that these dlls are not the same.What can I do to overcome this problem , can I change the Language property of dll files to become Language Specific ? Can this help ? <code> Compiler error ( s ) encountered processing expression `` testExpression '' . The project already has a reference to assembly MyProject.resources . A second reference to ' C : \Dlls\en-US\MyProject.resources.dll ' can not be added . at Microsoft.VisualBasic.Activities.VisualBasicHelper.Compile [ T ] ( LocationReferenceEnvironment environment , Boolean isLocationReference ) at Microsoft.VisualBasic.Activities.VisualBasicHelper.Compile [ T ] ( LocationReferenceEnvironment environment ) | WF 4 error with language specific resource dlls |
C_sharp : I always see singletons implemented like this : Is there 's something wrong with implementing it like this : ? It gets lazy initialized on the very same moment as in the first implementation so I wonder why this is n't a popular solution ? It should be also faster because there 's no need for a condition , locking and the field is marked as readonly which will let the compiler to do some optimisationsLet 's not talk about the singleton ( anti ) pattern itself , please <code> public class Singleton { static Singleton instance ; static object obj = new object ( ) ; public static Singleton Instance { get { lock ( obj ) { if ( instance == null ) { instance = new Singleton ( ) ; } return instance ; } } } protected Singleton ( ) { } } public class Singleton { static readonly Singleton instance = new Singleton ( ) ; public static Singleton Instance { get { return instance ; } } protected Singleton ( ) { } } | Singleton shortened implementation |
C_sharp : I 'm creating an ASP.net website which handles thousands of requests and it all stems from one main object that they all share to read it . I 'm trying to wrap my head around these different types of locks.Some common questions i have for each.What is the scope of each lock Application , Session , ObjectWhen is it right to use one over the other ? Can multiple users run the code in the lock at one time ? Performance Hit ? 1.2.3.4 . <code> public class MyClass { lock { // DO COOL CODE STUFF . } } public class MyClass { Application.Lock // DO COOL CODE STUFF . Application.Unlock } public static object lockObject = new object ( ) ; public class MyClass { lock ( lockObject ) { // DO COOL CODE STUFF . } } private static readonly ReaderWriterLockSlim slimLock = new ReaderWriterLockSlim ( ) ; public class MyClass { slimLock.EnterWriteLock ( ) ; // DO COOL CODE STUFF HERE . slimLock.ExitWriteLock ( ) ; } | understanding Locking help ? |
C_sharp : Question : Is this code look alright ? I understand that to be a key in the Map , Foo needs to override equals and hashcode methods - either override both or none.I was wondering what about List of objects as keys ? What does equality means when it comes to List ? is the map defined above safe from `` object-lost-in-the-map '' problem ? -Karephul <code> // No overrides required .. let CLR take care of equal and hashcode.Class Foo { public Name { get ; set ; } public Address { get ; set ; } } Dictionary < List < Foo > , int > map = new Dictionary < List < Foo > , int > ( ) ; | Can I use List of objects as Dictionary Keys ? |
C_sharp : I want to take a List of strings with around 12 objects and split it into two List of strings but completely randomise it.Example of List : List 1 : Apply some logic here ... Result gives me two lists : List 1 : List 2 : I 'm a newbie to C # MVC , so I 've found some answers on Stack but none have been able to answer my question.Edit : What I 've tried so far gives me one random member of the team . I want to now expand on this and create the two lists as mentioned above . *EDIT** Thanks for the solution ! I 've now got my application working and managed to publish it to the web , https : //www.teamgenerator.online . <code> EXAMPLE 1EXAMPLE 2EXAMPLE 3EXAMPLE 4EXAMPLE 5EXAMPLE 6EXAMPLE 7EXAMPLE 8 EXAMPLE 5EXAMPLE 6EXAMPLE 1EXAMPLE 8 EXAMPLE 2EXAMPLE 3EXAMPLE 4EXAMPLE 7 [ HttpPost ] public ActionResult Result ( Models.TeamGenerator model ) { var FormNames = model.Names ; string [ ] lines = FormNames.Split ( new [ ] { Environment.NewLine } , StringSplitOptions.None ) ; List < string > listOfLines = new List < string > ( ) ; foreach ( var i in lines ) { listOfLines.Add ( i ) ; } string [ ] result1 = listOfLines.Where ( item = > item ! = string.Empty ) .ToArray ( ) ; Random genRandoms = new Random ( ) ; int aRandomTeam = genRandoms.Next ( listOfLines.Count ) ; string currName = listOfLines [ aRandomTeam ] ; return View ( ) ; } | Create two random lists from one list |
C_sharp : Back in the old days of C , one could use array subscripting to address storage in very useful ways . For example , one could declare an array as such . This array represents an EEPROM image with 8 bit words.And later refer to that array as if it were really multi-dimensional storage I 'm sure I have the syntax wrong , but I hope you get the idea . Anyway , this projected a two dimension image of what is really single dimensional storage . The two dimensional projection represents the EEPROM image when loaded into the memory of an MPU with 16 bit words.In C one could reference the storage multi-dimensionaly and change values and the changed values would show up in the real ( single dimension ) storage almost as if by magic . Is it possible to do this same thing using C # ? Our current solution uses multiple arrays and event handlers to keep things synchronized . This kind of works but it is additional complexity that we would like to avoid if there is a better way . <code> BYTE eepromImage [ 1024 ] = { ... } ; BYTE mpuImage [ 2 ] [ 512 ] = eepromImage ; | Question about array subscripting in C # |
C_sharp : I have a binding : and this C # code : Note that GridLength is a structure : https : //docs.microsoft.com/en-us/dotnet/api/xamarin.forms.gridlength ? view=xamarin-formsDoes anyone know how I can bind to the value marked with ? ? ? For more explanation here 's what I am trying to do : I would like to be able to set the width of the input box frames . Here in this example they are all the same width . <code> public static readonly BindableProperty EntryWidthProperty = BindableProperty.Create ( nameof ( EntryWidth ) , typeof ( int ) , typeof ( SingleEntryGrid ) , 150 , BindingMode.TwoWay ) ; public int EntryWidth { get = > ( int ) GetValue ( EntryWidthProperty ) ; set = > SetValue ( EntryWidthProperty , value ) ; } var column3 = new ColumnDefinition ( ) { Width = new GridLength ( ? ? ? , GridUnitType.Absolute ) } ; | How can I bind to a Grid ColumnDefinition Width in C # |
C_sharp : I assume the following sample gives a best practice that we should follow when we implement the IEnumerable interface.https : //docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenextHere is the question : Why should we provide two version of Current method ? When the version ONE ( object IEnumerator.Current ) is used ? When the version TWO ( public Person Current ) is used ? How to use PeopleEnum in the foreach statement . // updated <code> public class PeopleEnum : IEnumerator { public Person [ ] _people ; // Enumerators are positioned before the first element // until the first MoveNext ( ) call . int position = -1 ; public PeopleEnum ( Person [ ] list ) { _people = list ; } public bool MoveNext ( ) { position++ ; return ( position < _people.Length ) ; } public void Reset ( ) { position = -1 ; } // explicit interface implementation object IEnumerator.Current /// **version ONE** { get { return Current ; } } public Person Current /// **version TWO** { get { try { return _people [ position ] ; } catch ( IndexOutOfRangeException ) { throw new InvalidOperationException ( ) ; } } } } | C # - Why implement two version of Current when realizing IEnumerable Interface ? |
C_sharp : Based on random Internet comments , I 've always believed that the C # compiler does simple optimizations to the IL ( removing always-true if-statements , simple inlining , etc ) , then later the JIT performs the real , complex optimizations.As just one example , on the documentation for the /optimize compiler flag , it says The /optimize option enables or disables optimizations performed by the compiler to make your output file smaller , faster , and more efficient.which implies that at least some optimizations are applied by the language compiler.However , playing around with Try Roslyn , this appears to be not true . It looks like the C # compiler does literally no optimizations at all.ExamplesInput : Decompiled output : Input : Decompiled output : Input : Decompiled output : As you can see , the C # language compiler appears to do no optimizations at all.Is this true ? If so , why does the documentation claim that /optimize will make your executable smaller ? <code> bool y = true ; if ( y ) Console.WriteLine ( `` yo '' ) ; if ( true ) { Console.WriteLine ( `` yo '' ) ; } static void DoNothing ( ) { } static void Main ( string [ ] args ) { DoNothing ( ) ; Console.WriteLine ( `` Hello world ! `` ) ; } private static void DoNothing ( ) { } private static void Main ( string [ ] args ) { NormalProgram.DoNothing ( ) ; Console.WriteLine ( `` Hello world ! `` ) ; } try { throw new Exception ( ) ; } catch ( Exception ) { Console.WriteLine ( `` Hello world ! `` ) ; } try { throw new Exception ( ) ; } catch ( Exception ) { Console.WriteLine ( `` Hello world ! `` ) ; } | Does the C # language compiler perform any actual optimizations on its own ? |
C_sharp : Word seems to use a different apostrophe character than Visual Studio and it is causing problems with using Regex . I am trying to edit some Word documents in C # using OpenXML . I am basically replacing [ [ COMPANY ] ] with a company name . This has worked pretty smoothly until I have reached my corner case of companies with names that end in s. I end up with issue s where sometimes it creates a s 's . Example : Company Name : Simmons Text in Doc : The [ [ COMPANY ] ] 's business is cars . Result : The Simmons 's business is cars.This is improper English . I should be able to just use a basic find and replace like I did for [ [ COMPANY ] ] , but it is not working . This does not . It seems that Word is using an different character for and apostrophe ( ' ) than the standard one that is created when I use the key on my keyboard in Visual Studio . If I write a find and replace using my keyboard it will not work , but if I copy and paste the apostrophe from Word it does . Notice the different character in the Regex for the second one . I 'm confused as to why this is , and also want to know if the is a proper way of doing this . I tried `` ' '' but that does not work . I just want to know if using the copied character from Word is the proper way of doing this , and is there a way to do it so that both characters work so I do n't have an issue with docs that may be created with a different program . <code> Regex apostropheReplace = new Regex ( `` s\\ 's '' ) ; docText = apostropheReplace.Replace ( docText , `` s\ ' '' ) ; Regex apostrophyReplace = new Regex ( `` s\\ ’ s '' ) ; docText = apostrophyReplace.Replace ( docText , `` s\ ' '' ) ; | Issue with find and replace apostrophe ( ' ) in a Word Docx using OpenXML and Regex |
C_sharp : I 'm experimenting with locks that do n't require atomic instructions . Peterson 's algorithm seemed like the simplest place to start . However , with enough iterations , something goes wrong.Code : When I run this , I consistently get < 2,000,000 . What 's going on ? <code> public class Program { private static volatile int _i = 0 ; public static void Main ( string [ ] args ) { for ( int i = 0 ; i < 1000 ; i++ ) { RunTest ( ) ; } Console.Read ( ) ; } private static void RunTest ( ) { _i = 0 ; var lockType = new PetersonLock ( ) ; var t1 = new Thread ( ( ) = > Inc ( 0 , lockType ) ) ; var t2 = new Thread ( ( ) = > Inc ( 1 , lockType ) ) ; t1.Start ( ) ; t2.Start ( ) ; t1.Join ( ) ; t2.Join ( ) ; Console.WriteLine ( _i ) ; } private static void Inc ( int pid , ILock lockType ) { try { for ( int i = 0 ; i < 1000000 ; i++ ) { lockType.Request ( pid ) ; _i++ ; lockType.Release ( pid ) ; } } catch ( Exception ex ) { Console.WriteLine ( ex ) ; } } } public interface ILock { void Request ( int pid ) ; void Release ( int pid ) ; } public class NoLock : ILock { public void Request ( int pid ) { } public void Release ( int pid ) { } } public class StandardLock : ILock { private object _sync = new object ( ) ; public void Request ( int pid ) { Monitor.Enter ( _sync ) ; } public void Release ( int pid ) { Monitor.Exit ( _sync ) ; } } public class PetersonLock : ILock { private volatile bool [ ] _wantsCs = new bool [ 2 ] ; private volatile int _turn ; public void Request ( int pid ) { int j = pid == 1 ? 0 : 1 ; _wantsCs [ pid ] = true ; _turn = j ; while ( _wantsCs [ j ] & & _turn == j ) { Thread.Sleep ( 0 ) ; } } public void Release ( int pid ) { _wantsCs [ pid ] = false ; } } | Why does Peterson 's lock fail in this test ? |
C_sharp : I mostly understand deferred execution , but I have a question about a particular case : Given a code fragment such ashow many times is the query resultsOfInterest executed ? Once when setting up the foreach loop , or once for every element ' x ' ? Would it be more efficient with ? TIA <code> var resultsOfInterest = from r in ... select r ; foreach ( var x in resultsOfInterest ) { //do something with x } foreach ( var x in resultsOfInterest.ToArray ( ) ) { //do something with x } | Linq deferred operations |
C_sharp : I want to create a library that will create objects using a user-defined function and modify them using another user-defined function . I have an OCaml background and see a fairly straightforward way to implement it : The problem is that I want that library to be easy to call from C # : having functions as arguments is probably a bad idea.Interface and abstract class ( that would be inherited by userType ) seems to be the usual OO solution , but I can not initialize an object if I do n't know the ( not yet defined ) userType making the initialization step , inside my function , impossible.The only workaround that I can think of is to ask the user for an instance of his userType as an argument that would be used to call initialization , but that seems very inelegant.Is there a way to solve this problem ? <code> //user sidetype userType = { mutable time : float } let userInitialization ( ) = { time = 0 . } let userModification t = t.time < - t.time+1.//my sidelet algo initialization modification n = let a = Array.init n ( fun _ - > initialization ( ) ) modification a . [ 0 ] a | OO alternative to polymorphism in F # when calling F # from C # |
C_sharp : I was wondering why ReSharper does warn me , when I 'm trying to convert a char to a string without giving a specific culture info.Is there any case , where it could be converted differently on two systems ? Example : The following ReSharper warning will pop up by default : Specify a culture in string conversion explicitly . <code> var str = ' '.ToString ( ) ; | Why does ReSharper warn at Char.ToString ( ) when not specifying CultureInfo explicitly ? |
C_sharp : I can refactor this code ( popular as/null check pattern ) ..into a nice `` is '' type pattern expression : ..which is cool ... I think ... Is it ? But now I am also thinking to refactor..into : Note : there is no as and SomeMethod ( ) already returns MyType . It looks like ( pseudocode ) if ( A is A ) and may easily confuse , no ? The first refactoring is legal , but what about the latter one ? I am not an IL expert to check myself and C # 7.0 features are still new to me . Perhaps there are problems which I did n't discover yet ? <code> var a = b as MyType ; if ( a ! = null ) { ... } if ( b is MyType a ) { ... } var a = SomeMethod ( ) ; if ( a ! = null ) { ... } if ( SomMethod ( ) is MyType a ) { ... } | The `` is '' type pattern expression for null check |
C_sharp : I 'm curious if it is possible to determine whether or not an Assembly has referenced a particular class or not . I 'm currently using Reflection to load Assemblies and then I determine what Assemblies are being referenced from within the assembly I am loading : Now that I know what Assemblies are referenced , I want to dig into those vReferencedAssembly and determine if something like this occurs : In simple english , I do n't want to load an Assembly from a list supplied to me that may contain what I consider a threat . So I may want to block things that may manipulate files and so forth . <code> foreach ( var vReferencedAssembly in vSomeAssembly.GetReferencedAssemblies ( ) ) File.Create ( vSomeFile ) ; | Determining if a class is referenced C # |
C_sharp : I am developing a program which uses visual styles . The Main method looks like this : The program also works as a plugin of another application and it is started , in this case , via COM . The problem is that the calling application ( the COM client ) does n't call EnableVisualStyles and it is out of my control . In this case the program is started as follows : When the program is started as a plugin the progress bars and the combo boxes are not rendered with the same style they have when the program is started normally , while buttons , check boxes and radio buttons are OK.Is there a way to force the visual style ? I 've tried with a manifest but with no luck ! Here is the manifest that I tried : I think that the manifest is embedded correctly because ildasm shows the following in the manifest section : Thanks , Stenio <code> [ STAThread ] static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Application.Run ( new Form ( ) ) ; } public static void StartAsPlugin ( ) { Application.EnableVisualStyles ( ) ; Form form = new Form ( ) ; form.ShowDialog ( ) ; } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < assembly xmlns= '' urn : schemas-microsoft-com : asm.v1 '' manifestVersion= '' 1.0 '' > < assemblyIdentity version= '' 1.0.0.0 '' processorArchitecture= '' * '' name= '' RealApp '' type= '' win32 '' / > < description > Your application description here. < /description > < dependency > < dependentAssembly > < assemblyIdentity type= '' win32 '' name= '' Microsoft.Windows.Common-Controls '' version= '' 6.0.0.0 '' processorArchitecture= '' * '' publicKeyToken= '' 6595b64144ccf1df '' language= '' * '' / > < /dependentAssembly > < /dependency > < /assembly > .mresource public RealApp.RealApp.exe.manifest { // Offset : 0x000004F0 Length : 0x0000029B } | Visual styles do n't work on an in-process COM server |
C_sharp : In Visual Studio 2013 Ultimate , Microsoft introduced a feature named CodeLens . A handy feature which ( among others ) has the ability to count the number of times a method is referenced in your project . At the moment we 're using VS2015 Pro and I 'm working in a big solution with multiple projects in it . The problemConsider the following class : CodeLens would count the number of times every property is referenced and adds it above each properties ' declaration . I 've also overridden the ToString ( ) method to easily read the values when printing.Right now , every time when I open a file with a ToString ( ) declaration or when I make changes to one , Visual Studio starts counting the references of every occasion where ToString ( ) is used . Even when this specific method in this class is not used . This results in Visual Studio using all my CPU ( 95 % + ) and becoming unresponsive for a few minutes.My QuestionI have already learned how to disable CodeLens reference counting completely , but this is not what I want . What I would like to know is if there is any way to tell CodeLens to stop reference counting for a single method in general , and ToString ( ) specifically ( an attribute or blacklist perhaps ? ) . This way Visual Studio wo n't have to go through the hassle of counting every time an overridden method is referenced . Alternatively , I would like to see the amount of references to MapItem.ToString ( ) only . <code> public class MapItem { public int Id { get ; set ; } public string Provider { get ; set ; } public string Value { get ; set ; } public bool MainItem { get ; set ; } public int ? MapId { get ; set ; } public override string ToString ( ) { return $ '' Provider : { Provider } , Value : { Value } , MainItem : { MainItem } '' ; } } | Prevent Visual Studio from counting references of certain methods |
C_sharp : I have some code that I have no control of . This code accepts an object parameter and attempts to cast it to a type known at compile time like this : Is it possible in C # to design a custom class MyClass ( not derived from KnownType ) that can be passed as parameter to the above code and be converted to KnownType by the above code , provided that MyClass can convert itself to KnownType using its member method : I have tried to implement a custom conversion operator like this : but it did n't work ( it was not used ) . Am I right to assume that the cast operator only works when the source type , target type and conversion operators are known at compile time ? Edit : I initially did n't provide more details about the code doing the conversion because I think it is irrelevant and because I am mainly interested in the way the cast operator is implemented , i.e . does it take look at the runtime type to find an appropriate converter or is the decision made at compile time ? To clear things out , KnownType is in fact DataRowView , while MyClass is a wrapper class for DataRowView that has to derive from some other type . MyClass keeps a reference to a DataRowView . Instead of binding ComboBox.DataSource to a DataView , I bind it to an IList < MyClass > but I still need the ComboBox to be able to access the DataRowView column values as if I was binding an IList < DataRowView > . Unfortunately the cast operator works the way I was afraid it would : it only takes into account compile time type information to do conversions ( it does however use runtime type information when casting between types in the same inheritance tree ) . <code> KnownType item = ( KnownType ) parameter ; protected KnownType ConvertToKnownType ( ) { // conversion code goes here } public static implicit operator KnownType ( MyClass source ) { KnownType result ; // conversion goes here return result ; } | C # dynamic conversion through cast operator |
C_sharp : Consider the following scenario of services and components in a sample C # console application Let 's imagine to do the following registrations inside the composition root : This kind of scenario works fine and I did so several times.What if , for some reason , I would like to inject inside the constructor of Consumer class only two different implementations of IService , for instance only FooService and BarService ( while still continuing to inject all the available implementations of IService inside the constructor of AnotherConsumer ) ? Is there an elegant way to do so ? <code> public interface IService { } public class FooService : IService { } public class BarService : IService { } public class BuzzService : IService { } public class AwesomeService : IService { } public class Consumer { public Consumer ( IEnumerable < IService > services ) { // do some initilization work here ... } } public class AnotherConsumer { public AnotherConsumer ( IEnumerable < IService > services ) { // do some initilization work here ... } } var container = new WindsorContainer ( ) ; container.Kernel.Resolver.AddSubResolver ( new CollectionResolver ( container.Kernel , true ) ) ; container.Register ( Component.For < IService > ( ) .ImplementedBy < FooService > ( ) ) ; container.Register ( Component.For < IService > ( ) .ImplementedBy < BarService > ( ) ) ; container.Register ( Component.For < IService > ( ) .ImplementedBy < BuzzService > ( ) ) ; container.Register ( Component.For < IService > ( ) .ImplementedBy < AwesomeService > ( ) ) ; container.Register ( Component.For < Consumer > ( ) ) ; container.Register ( Component.For < AnotherConsumer > ( ) ) ; // consumer got injected all 4 different implementations of IService// due to CollectionResolvervar consumer = container.Resolve < Consumer > ( ) ; // anotherConsumer got injected all 4 different implementations of // IService due to CollectionResolvervar anotherConsumer = container.Resolve < AnotherConsumer > ( ) ; | Castle Windsor : inject IEnumerable < IService > using only a subset of registered components for IService |
C_sharp : I was curious on the overhead of a large structure vs. a small structure in using operators + and * for math . So I made two struct , one Small with 1 double field ( 8 bytes ) and one Big with 10 doubles ( 80 bytes ) . In all my operations I only manipulate one field called x.First I defined in both structures mathematical operators likewhich as expected use up a lot of memory in the stack for copying fields around . I run 5,000,000 iterations of a mathematical operation and got what I suspected ( 3 times slowdown ) .results from Release code ( in seconds ) Now for the interesting part . I define the same operations with static methods with ref argumentsand run the same number of iterations on this test code : And the results show ( in seconds ) So compared to the mem-copy intensive operators I get a speedup of x3 and x14 which is great , but compare the Small struct times to the Big and you will see that Small is 60 % slower than Big.Can anyone explain this ? Does it have to do with CPU pipeline and separating out operations in ( spatially ) memory makes for more efficient pre-fetch of data ? If you want to try this for yourself grab the code from my dropbox http : //dl.dropbox.com/u/11487099/SmallBigCompare.zip <code> public static Small operator + ( Small a , Small b ) { return new Small ( a.x + b.x ) ; } public static Small operator * ( double x , Small a ) { return new Small ( x * a.x ) ; } public double TestSmall ( ) { pt.Start ( ) ; // pt = performance timing object Small r = new Small ( rnd.NextDouble ( ) ) ; //rnd = Random number generator for ( int i = 0 ; i < N ; i++ ) { a = 0.6 * a + 0.4 * r ; // a is a local field of type Small } pt.Stop ( ) ; return pt.ElapsedSeconds ; } Small=0.33940 Big=0.98909 Big is Slower by x2.91 public static void Add ( ref Small a , ref Small b , ref Small res ) { res.x = a.x + b.x ; } public static void Scale ( double x , ref Small a , ref Small res ) { res.x = x * a.x ; } public double TestSmall2 ( ) { pt.Start ( ) ; // pt = performance timing object Small a1 = new Small ( ) ; // local Small a2 = new Small ( ) ; // local Small r = new Small ( rnd.NextDouble ( ) ) ; //rdn = Random number generator for ( int i = 0 ; i < N ; i++ ) { Small.Scale ( 0.6 , ref a , ref a1 ) ; Small.Scale ( 0.4 , ref r , ref a2 ) ; Small.Add ( ref a1 , ref a2 , ref a ) ; } pt.Stop ( ) ; return pt.ElapsedSeconds ; } Small=0.11765 Big=0.07130 Big is Slower by x0.61 | Peculiar result relating to struct size and performance |
C_sharp : I 'm trying to check if an enum option is contained in the available options.Its a little bit difficult for me to explain it in english.Here 's the code : I 'm trying to check if the me varliable is contained in the available variable.I know it can be done because it 's used with the RegexOptions too . <code> public enum Fruits { Apple , Orange , Grape , Ananas , Banana } var available = Fruits.Apple | Fruits.Orange | Fruits.Banana ; var me = Fruits.Orange ; | c # check enum is contained in options |
C_sharp : I 'm in need to create a method which allows me to populate a List < string > with the values of the constants that are defined in the own class.To give you a quick example of the numerous ( 20 in total ) constants that are defined in the class : As you can see , the name of the constant equals the value of it , if that can help.So far , looking at examples of different types of solutions that I 've found in StackOverflow about similar problems , I 've come up with this : My experience as a programmer is quite low , same as my experience with C # ; I 'm not sure if type.GetType ( ) .GetProperties ( ) references the constant names , same happens with the property.Name line.Does this method do what I 'm asking ? <code> private const string NAME1 = `` NAME1 '' ; private const string NAME2 = `` NAME2 '' ; private const string NAME3 = `` NAME3 '' ; ... public static List < string > GetConstantNames ( ) { List < string > names = new List < string > ( ) ; Type type = typeof ( ClassName ) ; foreach ( PropertyInfo property in type.GetType ( ) .GetProperties ( ) ) { names.Add ( property.Name ) ; } return names ; } | Method to populate a List < string > with class constant values . C # |
C_sharp : I am trying to dynamically get the schema of one of my views in SQLite using C # . I am using this code : Its working perfectly for all my tables and views except for one view . For some reason , the data type for the field called SaleAmount is coming up blank . There is nothing in the row [ `` DATA_TYPE '' ] element.Here is my view : I am using the standard System.Data.SQLite libraries . Anyone have any idea why this would come up blank ? Like I said , it is happening only on this one field in this one view.UPDATEI figured out how to duplicate the issue . Apparently if a view contains an aggregate function , such as Sum , GetSchema returns an empty data type . Anyone know of a workaround ? <code> using ( var connection = new SQLiteConnection ( ConnectionString ) ) { connection.Open ( ) ; using ( DataTable columns = connection.GetSchema ( `` Columns '' ) ) { foreach ( DataRow row in columns.Rows ) { string dataType = ( ( string ) row [ `` DATA_TYPE '' ] ) .Trim ( ) ; // doing irrelevant other stuff here } } } SELECT [ Order Subtotals ] .Subtotal AS SaleAmount , Orders.OrderID , Customers.CompanyName , Orders.ShippedDateFROM Customers JOIN Orders ON Customers.CustomerID = Orders.CustomerIDJOIN [ Order Subtotals ] ON Orders.OrderID = [ Order Subtotals ] .OrderID WHERE ( [ Order Subtotals ] .Subtotal > 2500 ) AND ( Orders.ShippedDate BETWEEN DATETIME ( '1997-01-01 ' ) And DATETIME ( '1997-12-31 ' ) ) | ADO.Net reporting empty data type in SQLite |
C_sharp : I was thinking about GUIDs recently , which led me to try this code : You can see that all of the bytes are there , but half of them are in the wrong order when I use BitConverter.ToString . Why is this ? <code> Guid guid = Guid.NewGuid ( ) ; Console.WriteLine ( guid.ToString ( ) ) ; //prints 6d1dc8c8-cd83-45b2-915f-c759134b93aaConsole.WriteLine ( BitConverter.ToString ( guid.ToByteArray ( ) ) ) ; //prints C8-C8-1D-6D-83-CD-B2-45-91-5F-C7-59-13-4B-93-AAbool same=guid.ToString ( ) ==BitConverter.ToString ( guid.ToByteArray ( ) ) ; //falseConsole.WriteLine ( same ) ; | Why are these two strings not equal ? |
C_sharp : In my quest to the primes , I 've already asked this question : Ca n't create huge arrays which lead me to create my own class of fake arrays based on a dictionary of arrays ... : private Dictionary < int , Array > arrays = new Dictionary < int , Array > ( ) ; I can know create fake arrays of a lot of bool ( like 10 000 000 000 ) using the code below : But it crashes as soon as I ask for a CustomArray of 100 000 000 000 elements . It works well for the 25 first iterations ( my Dictionary contains 25 arrays of 0x7FFFFFC7 elements ) but then it crashes with an OutOfMemory exception.As a remainder , I 've got 16GB memory , VS2013 , the program is compiled in 64bits , I 've enabled the gcAllowVeryLargeObjects option and I do n't see any memory peak in the Task Manager . How can I avoid this error ? <code> public class CustomArray { private Dictionary < int , Array > arrays = new Dictionary < int , Array > ( ) ; public CustomArray ( ulong lenght ) { int i = 0 ; while ( lenght > 0x7FFFFFC7 ) { lenght -= 0x7FFFFFC7 ; arrays [ i ] = new bool [ 0x7FFFFFC7 ] ; i++ ; } arrays [ i ] = new bool [ lenght ] ; } } | Create huge dictionary |
C_sharp : I have the following input text : I would like to parse the values with the @ name=value syntax as name/value pairs . Parsing the previous string should result in the following named captures : I tried the following regex , which got me almost there : The primary issue is that it captures the opening quote in `` John \ '' '' The Anonymous One\ '' '' Doe '' . I feel like this should be a lookbehind instead of a lookahead , but that does n't seem to work at all.Here are some rules for the expression : Name must start with a letter and can contain any letter , number , underscore , or hyphen.Unquoted must have at least one character and can contain any letter , number , underscore , or hyphen.Quoted value can contain any character including any whitespace and escaped quotes.Edit : Here 's the result from regex101.com : <code> @ '' This is some text @ foo=bar @ name= '' '' John \ '' '' The Anonymous One\ '' '' Doe '' '' @ age=38 '' name : '' foo '' value : '' bar '' name : '' name '' value : '' John \ '' '' The Anonymous One\ '' '' Doe '' name : '' age '' value : '' 38 '' @ '' ( ? : ( ? < =\s ) |^ ) @ ( ? < name > \w+ [ A-Za-z0-9_- ] + ? ) \s*=\s* ( ? < value > [ A-Za-z0-9_- ] +| ( ? = '' '' ) .+ ? ( ? = ( ? < ! \\ ) '' '' ) ) '' ( ? : ( ? < =\s ) |^ ) @ ( ? < name > \w+ [ A-Za-z0-9_- ] + ? ) \s*=\s* ( ? < value > ( ? < ! '' ) [ A-Za-z0-9_- ] +| ( ? = '' ) .+ ? ( ? = ( ? < ! \\ ) '' ) ) ( ? : ( ? < =\s ) |^ ) Non-capturing group @ matches the character @ literally ( ? < name > \w+ [ A-Za-z0-9_- ] + ? ) Named capturing group name\s* match any white space character [ \r\n\t\f ] = matches the character = literally\s* match any white space character [ \r\n\t\f ] Quantifier : * Between zero and unlimited times , as many times as possible , giving back as needed [ greedy ] ( ? < value > ( ? < ! '' ) [ A-Za-z0-9_- ] +| ( ? = '' ) .+ ? ( ? = ( ? < ! \\ ) '' ) ) Named capturing group value 1st Alternative : [ A-Za-z0-9_- ] + [ A-Za-z0-9_- ] + match a single character present in the list below Quantifier : + Between one and unlimited times , as many times as possible , giving back as needed [ greedy ] A-Z a single character in the range between A and Z ( case sensitive ) a-z a single character in the range between a and z ( case sensitive ) 0-9 a single character in the range between 0 and 9 _- a single character in the list _- literally 2nd Alternative : ( ? = '' ) .+ ? ( ? = ( ? < ! \\ ) '' ) ( ? = '' ) Positive Lookahead - Assert that the regex below can be matched `` matches the characters `` literally .+ ? matches any character ( except newline ) Quantifier : + ? Between one and unlimited times , as few times as possible , expanding as needed [ lazy ] ( ? = ( ? < ! \\ ) '' ) Positive Lookahead - Assert that the regex below can be matched ( ? < ! \\ ) Negative Lookbehind - Assert that it is impossible to match the regex below \\ matches the character \ literally `` matches the characters `` literally | Parsing text between quotes with .NET regular expressions |
C_sharp : I 'd like to do something like this : Note : I 'm running tasks on the thread pool , so there is no async context.I 'd like to be able to tell the difference between an exception thrown immediately , and I 'm still on the calling thread ( e.g . parameter is invalid causing the function to abort ) , and an exception thrown when the async task completes , and I 'm on some other random callback thread ( e.g . network failure ) I can work out how I might achieve this if I did n't use await , and just used ContinueWith on the async operation , but is it possible using await ? <code> public async Task < int > DoWork ( int parameter ) { try { await OperationThatMayCompleteSynchronously ( parameter ) ; } catch ( Exception ) e { if ( completedSynchronously ) doSyncThing ( ) ; else doAsyncThing ( ) ; } } | async await exception catching - which thread am I on ? |
C_sharp : Is it sufficient to compare the ManagedThreadId at the time an object is created and at the time a method is called to verify that it is n't being used in a multithreading scenario ? My intuition is often wrong about threading , so I wanted to check to see if there are edge cases I should be keeping in mind . <code> public class SingleThreadSafe { private readonly int threadId ; public SingleThreadSafe ( ) { threadId = Thread.CurrentThread.ManagedThreadId ; } public void DoSomethingUsefulButNotThreadSafe ( ) { if ( threadId ! =Thread.CurrentThread.ManagedThreadId ) { throw new InvalidOperationException ( `` This object is being accessed by a thread different than the one that created it. `` + `` But no effort has been made to make this object thread safe . `` ) ; } //Do something useful , like use a previously established DbConnection } } | How do I detect multi-threaded use ? |
C_sharp : I ca n't quite explain to myself in clear terms why a Task spawn by a Timer works just fine but a Timer spawn by a Task does NOT.All relevant code is included below so you can easily reproduce it.Form.cs : ProcessDelayList.cs : ProcessDelay.cs : <code> private void Form1_Load ( object sender , EventArgs e ) { ProcessDelayList list = new ProcessDelayList ( ) ; foreach ( ProcessDelay p in list ) { //this works p.Start ( ) ; //this does NOT work //Task.Factory.StartNew ( ( ) = > p.Start ( ) ) ; } } public class ProcessDelayList : List < ProcessDelay > { public ProcessDelayList ( ) { Add ( new ProcessDelay ( `` Process 1 '' , 2000 ) ) ; Add ( new ProcessDelay ( `` Process 2 '' , 4000 ) ) ; Add ( new ProcessDelay ( `` Process 3 '' , 6000 ) ) ; Add ( new ProcessDelay ( `` Process 4 '' , 8000 ) ) ; Add ( new ProcessDelay ( `` Process 5 '' , 10000 ) ) ; } } public class ProcessDelay { private string name ; private int delay ; private Timer timer ; public ProcessDelay ( string name , int delay ) { this.name = name ; this.delay = delay ; } public void Start ( ) { timer = new Timer ( ) ; timer.Interval = delay ; timer.Tick += timer_Tick ; timer.Start ( ) ; } private void timer_Tick ( object sender , EventArgs e ) { //these work either way , as long as the task // is NOT spawn in the main loop . //TimerProc ( ) ; TimerProcTask ( ) ; } private void TimerProcTask ( ) { Task.Factory.StartNew ( ( ) = > TimerProc ( ) ) ; } private void TimerProc ( ) { timer.Stop ( ) ; MessageBox.Show ( name , delay.ToString ( ) ) ; } } | Timer Spawn By Task And Task Spawn By Timer |
C_sharp : I have the following line of code , with works in VS 2015 and .Net 4.0 , but I am getting an error in VS 2013.Why it works in a different way ? <code> StringBuilder s = new StringBuilder ( `` test '' ) { [ 0 ] = 'T ' } ; | StringBuilder initializer works one way in VS2015 but another in VS2013 |
C_sharp : Given this Java code , this outputs 0 and 4 : And with this identical C # code , this outputs 4 and 4using System ; Though I figure out that the output should be 4 and 4 on Java , but the answer is actually 0 and 4 on Java . Then I tried it in C # , the answer is 4 and 4What gives ? Java rationale is , during construction of B , A is still initializing ( consequently I posit B is still initializing if Java said A is still initializing ) , so the default value should be 0 . Hence the output is 0 and 4 in Java.Why C # constructor behavior differs from Java , or vice-versa ? <code> class A { A ( ) { print ( ) ; } void print ( ) { System.out.println ( `` A '' ) ; } } class B extends A { int i = Math.round ( 3.5f ) ; public static void main ( String [ ] args ) { A a = new B ( ) ; a.print ( ) ; } void print ( ) { System.out.println ( i ) ; } } class A { internal A ( ) { print ( ) ; } virtual internal void print ( ) { Console.WriteLine ( `` A '' ) ; } } class B : A { int i = ( int ) Math.Round ( 3.5f ) ; public static void Main ( string [ ] args ) { A a = new B ( ) ; a.print ( ) ; } override internal void print ( ) { Console.WriteLine ( i ) ; } } | Java constructor is not so intuitive . Or perhaps it 's not Java , it 's C # that is not intuitive |
C_sharp : That 's the best way I could think to ask the question , the detail is below . It 's taken me an hour just to figure out how to ask the question ! Let 's say that I have 5 ( or more ) types of text files - they are generated by a scientific instrument and each has certain results . Let 's call these `` types '' A , B , C , D , E. The actual names of the text files do n't give this away so the user ca n't easily see what they are just by the name . If it makes it easier , we could just consider a list of `` strings '' . { I have NO idea what to do about replcate types but I 'll worry about that later ) I wish to give the user the option to combine the text files into a conglomerate file but the challenge is , it does n't make sense to combine certain types ( for reasons that I do n't feel it worthwhile to go into ) .I 've constructed and example matrix of compatibilitySo , this is saying that I could combine A with B , C , D but not E ( and so on ) .Now if a user chooses files that have types `` A , B and C '' from a list of files ( that are n't obviously typed ) I would like to check the selections and say `` yes , ABC is a legal merge '' and perform the merge.If the user selects A , B , C , D , I would like to say , NO , you ca n't do that as D is not compatible with B - however , you could do A , B , C or A , C , D ( as D should not be where B would be ) .Still with me ? I created the above matrix in code and have got to a looping structure where I started to get a bit muddled and thought I might ask for some help before I find myself losing my home and family . I 've got a fairly large comment section on how I 'm trying to make choices . Remember that `` A '' could be `` Dog '' and `` B '' could be `` Cat '' etc.I hope this is clear . So What is the best way to achieve such a task ? Recursion , LINQ `` Magic '' , matrix math ? [ EDIT : ] An idea I just had that may be easier to implement , might be to Show a list of files and as a user selects them , I could `` deactivate '' the other choices that are n't compatible . Imagine a listBox or similar where you select an `` A '' type and if the above matrix is in play , type `` E '' files would be greyed out . I wonder if this will cause me less stress ... ? <code> A B C D E A 1 1 1 1 0 B 1 1 1 0 0 C 1 1 1 1 0 D 1 0 1 1 1 E 0 0 0 1 1 internal class CompatibilityCheck { private List < string > FileTypes ; public CompatibilityCheck ( ) { //Strings are unique types for text files FileTypes = new List < string > { `` A '' , `` B '' , `` C '' , `` D '' , `` E '' } ; int [ , ] CompatibilityMatrix = { { 1 , 1 , 1 , 1 , 0 } , { 1 , 1 , 1 , 0 , 0 } , { 1 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 , 1 } , { 0 , 0 , 0 , 1 , 1 } } ; /* Scenario 1 */ //List of file names from user = ALL LEGAL var userSelection = new List < string > { `` A '' , `` B '' , `` C '' } ; /* Go through each item in userSelection and make arrays of `` legal '' file combinations ? * start with A and find the compatible matches , B and C. Check that B and C are okay . * Answer should look like this as A , B and C can be combined */ /* Scenario 2 */ // List of file names from user = NOT ALL LEGAL = > D and B are incompatible var userSelection2 = new List < string > { `` A '' , `` B '' , `` C '' , `` D '' } ; /* In my head , I go through each item in userSelction2 * Take A and build `` A , B , C , D '' as it is compatible * check B with C ( yes ) and D ( no ) - remove D. * end [ A , B , C ] * * Start with B and build B , A , C * check A with C ( yes ) * end [ B , A , C ] * * Start with C and build C , A , B * check A with B ( yes ) * end [ C , A , B ] * * Start with D and build D , A , C * check A with C ( yes ) * end [ D , A , C ] * * take the nth string and compare to n+1 , n+2 ... n+ ( length-n ) * * the unique string sets woudld be A , B , C and A , C , D */ } } | How do I make a new list of strings from another list based on certain criteria ? |
C_sharp : I have an array of custom objects named AnalysisResult . The array can contain hundreds of thousands of objects ; and , occasionally I need only the Distinct ( ) elements of that array . So , I wrote a item comparer class called AnalysisResultDistinctItemComparer and do my call like this : My problem here is that this call can take a LONG time ( on the order of minutes ) when the array is particularly big ( greater than 200,000 objects ) . I currently call that method in a background worker and display a spinning gif to alert the user that the method is being performed and that the application has not frozen . This is all fine and well but it does not give the user any indication of the current progress.I really need to be able to indicate to the user the current progress of this action ; but , I have been unable to come up with a good approach . I was playing with doing something like this : But the problem is that I have no way of knowing what my actual progress is . Thoughts ? Suggestions ? <code> public static AnalysisResult [ ] GetDistinct ( AnalysisResult [ ] results ) { return results.Distinct ( new AnalysisResultDistinctItemComparer ( ) ) .ToArray ( ) ; } public static AnalysisResult [ ] GetDistinct ( AnalysisResult [ ] results ) { var query = results.Distinct ( new AnalysisResultDistinctItemComparer ( ) ) ; List < AnalysisResult > retVal = new List < AnalysisResult > ( ) ; foreach ( AnalysisResult ar in query ) { // Show progress here retVal.Add ( ar ) ; } return retVal.ToArray ( ) ; } | How to report progress on a long call to .Distinct ( ) in C # |
C_sharp : Edit # 2 : config.FilePath is showing that it 's looking at a different file than what I 'm expecting : `` C : \Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config '' . I was expecting it to use the web.config in my project . Need to figure out why that 's happening.I have a method in my web API where I 'm trying to read the values from the authorization section in my web.config . Based on what I 've found , this should work : And this is the section of the web.config that contains the authorization info : You can see that there is one allow and one deny . When I run the code , it appears that there is only one rule . Should n't there be two since there is an allow and a deny ? And the one rule looks to have an Action of Allow and `` * '' for Users . That 's not what 's in the web.config . What am I missing here ? ** Edit **I 've considered the possibility that it 's reading a different web.config file . But there is only one other web.config file in the solution ( under Views ) . I also changed it to have the same authorization section , but I still get the same result . <code> public AuthorizationSetting GetAuthorizationSettings ( ) { var config = WebConfigurationManager.OpenWebConfiguration ( null ) ; var section = config.GetSection ( `` system.web/authorization '' ) as AuthorizationSection ; foreach ( AuthorizationRule rule in section.Rules ) { if ( rule.Action.ToString ( ) .ToLower ( ) == `` allow '' ) { Debug.WriteLine ( rule ) ; } } return new AuthorizationSetting ( ) ; } < system.web > < compilation debug= '' true '' targetFramework= '' 4.5 '' / > < httpRuntime targetFramework= '' 4.5 '' / > < identity impersonate= '' true '' / > < authentication mode= '' Windows '' / > < authorization > < allow roles= '' role1 , role2 , role3 '' / > < deny users= '' * '' / > < /authorization > < /system.web > | Reading AuthorizationSection from web.config provides incorrect values |
C_sharp : I have written a piece of optimized code that contains special cases for null and empty strings . I am now trying to write a unit test for this code . In order to do that , I need two empty ( zero-length ) string objects that are different objects . Like this : It turns out that most .NET Framework APIs string are checking for an empty result . They are returning string.Empty in all those cases . For example , `` x '' .Remove ( 0 , 1 ) returns string.Empty.How can I create fresh zero-length string objects ? <code> string s1 , s2 ; Assert.IsTrue ( s1.Length == 0 & & s2.Length == 0 ) ; Assert.IsTrue ( ! ReferenceEquals ( s1 , s2 ) ) ; | How to manufacture an empty string in .NET ? |
C_sharp : I 'm not a C # guy I 'm more an Objective-C guy but lately I 've seen a lot of implementations of : Instead of : One of the examples of this is the MVVM Light Framework , there the developer implements the data service contract ( and implementation ) using the first approach , so my question is : Why this ? Is just a matter of likes or is the first approach asyncronous by defaut ( given the function pointer ) . If that 's true , is the standard return death ? I ask cause I personally like the second approach is more clear to me when I see an API . <code> public void Method ( Action < ReturnType > callback , params ... ) public ReturnType Method ( params ... ) | Action < T > vs Standard Return |
C_sharp : I have a text file which has lines of data separated by newlines . What I 'm trying to do is count the number of lines in the file , excluding the ones that are only a newline . I 'm trying to use a regular expression to look at each line as it is read , and if it starts with a newline character not include it in my line count , but I ca n't seem to get it to work . I 've searched all over the place for how to do this with no results.Here 's the method I 've written to try to do this : I 've tried changing the RegexOptions between Singleline andMultiline , I 've tried putting `` \r|\n|\r\n '' into my pattern match , and I 've tried removing the ^ from the expression , but I ca n't seem to get it to work . No matter what I do , my lineCount always ends up being the total number of lines in the file , including the newlines.I 'm apparently overlooking something obvious , but I 'm not yet familiar enough with the C # language to see what 's wrong . Everything looks like it should work to me . Can someone please help me out ? <code> public int LineCounter ( ) { StreamReader myRead = new StreamReader ( @ '' C : \TestFiles\test.txt '' ) ; int lineCount = 0 ; string line ; while ( ( line = myRead.ReadLine ( ) ) ! = null ) { string regexExpression = @ '' ^\r ? \n '' ; RegexOptions myOptions = RegexOptions.Multiline ; Match stringMatch = Regex.Match ( line , regexExpression , myOptions ) ; if ( stringMatch.Success ) { } else { lineCount++ ; } } return lineCount ; } | Match only a newline character |
C_sharp : Why C # compiler does not allow you to compile this : but does allow you to compile : where MyStruct is defined as : Update : in the firsts case the error is : Error 1 Use of unassigned local variable ' a ' <code> int a ; Console.WriteLine ( a ) ; MyStruct a ; Console.WriteLine ( a ) ; struct MyStruct { } | Differences between user created structs and framework structs in .NET |
C_sharp : I am a reasonably experiences hobby programmer , and I have good familiarity with C++ , D , Java , C # and others.With the exception of Go , almost every language requires me to explicitly state that I am implementing an interface . This is borderline ridiculous , since we today have compilers for languages like Haskell , which can do almost full-program type inference with very few hints.What I am looking for is a programming language that does this : What languages would see this , and automatically flag Test as implementing ITest ? ETA : I am not looking for duck typing . I am looking for strictly typed languages with inference . <code> interface ITest { void Test ( ) ; } class Test { void Test ( ) { } } void main ( ) { ITest x ; x = new Test ; } | What other languages support Go 's style of interfacing without explicit declaration ? |
C_sharp : I 'm attempting to add an error to the ModelState by using nameof : In the view , this has been tagged with a name of Foo.Bar . When I add a model state error , I have to key that error to a name , so I use nameof ( Foo.Bar ) - however this just gives me Bar , when I need Foo.Bar . Right now I can hardcode Foo.Bar but I 'd rather use a strongly-typed method . What are my options ? <code> @ Html.ValidationMessageFor ( m = > m.Foo.Bar ) | using nameof ( ) to inspect class name with its parent for MVC validation |
C_sharp : I have some code that takes a value ( of type object ) and tries to cast it to an IEnumerable of ints and uints like so : When the value is initialized this way : both idList and uintList have values , but calling idList.ToList ( ) results in an ArrayTypeMismatchException . However , when the value is generated with new List < uint > { number } , idList is null as expected . Additionally , calling var idList = value as IEnumerable < int > ; in the immediate window in VS 2015 returns null as I would expect , even when the value was generated with a collection initializer..Net fiddle reproducing the error here.What 's going on here ? <code> var idList = value as IEnumerable < int > ; var uintList = value as IEnumerable < uint > ; uint number = 1 ; object value = new [ ] { number } ; | Why does casting a value as IEnumerable < T > behave differently based on how I initialized the value ? |
C_sharp : Let say I have The question is are there two iterations or just one.In other words , is that equivalent in performance to : <code> IEnumerable < int > list = new int [ ] { 1 , 2 , 3 } ; List < int > filtered = list.Select ( item = > item * 10 ) .Where ( item = > item < 20 ) .ToList ( ) ; IEnumerable < int > list = new int [ ] { 1 , 2 , 3 } ; List < int > filtered = new List < int > ( ) ; foreach ( int item in list ) { int newItem = item * 10 ; if ( newItem < 20 ) filtered.Add ( newItem ) ; } | Does Select followed by Where result in two iterations over the IEnumerable ? |
C_sharp : I want to make it so that if the value of subs is not `` '' then the ULs go before and after it and into the variable sL . If subs is `` '' then sL get the value `` '' But it does n't seem to work . Is my format correct ? <code> var sL = ( subs ! = `` '' ) ? `` < ul > '' + subs + `` < /ul > '' : `` '' ; | Confused about the ? operator in c # |
C_sharp : I have a base abstract class and its abstract type parameter as : Then I have number of children classes inherent from it : Now , I want to put a Dictionary to keep track of the databases and a method to return them using DatabaseItem type , something like this : Then it gave me `` 'T ' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T ' '' error because DatabaseItem is abstract . I made DatabaseItem as non-abstract type , the error is gone but still lot of type conversion errors came out ... Found a similar question but I still not understand ... What 's the better solution/structure to achieve this ? <code> public abstract class Database < T > where T : DatabaseItem , new ( ) { protected List < T > _items = new List < T > ( ) ; protected virtual void Read ( string [ ] cols ) { T item = new T ( ) ; ... } public abstract class DatabaseItem { ... } public class ShopDatabase : Database < ShopItem > { } public class ShopItem : DatabaseItem { } public class WeaponDatabase : Database < WeaponItem > { } public class WeaponItem : DatabaseItem { } ... Dictionary < Type , Database < DatabaseItem > > databases ; public static Database < T > GetDatabase < T > ( ) where T : DatabaseItem { return databasebases [ typeof ( T ) ] ; } | Handling classes inherent from abstract class and type parameter |
C_sharp : I have a list of numbers and I want to find closest four numbers to a search number.For example if the search number is 400000 and the list is : { 150000 , 250000 , 400000 , 550000 , 850000 , 300000 , 200000 ) , then the closest 4 numbers would be : Any help or suggestion would be appreciated . <code> { 300000 , 400000 , 250000 , 550000 } | C # linq list find closest numbers |
C_sharp : I have an API call using SmartyAddress , here is the result returned from the API call : Now I would like to use JSON to return this result especially the analysis component , and here is the code I tried to write , but it always gives me the error : can not deserialize the current json object into type 'system.collections.generic.list and the following is the code : <code> [ { `` input_index '' : 0 , `` candidate_index '' : 0 , `` delivery_line_1 '' : `` xx '' , `` last_line '' : `` xx '' , `` delivery_point_barcode '' : `` xx '' , `` components '' : { `` primary_number '' : `` xx '' , `` street_name '' : `` xx '' , `` street_suffix '' : `` xx '' , `` city_name '' : `` xx '' , `` state_abbreviation '' : `` xx '' , `` zipcode '' : `` xx '' , `` plus4_code '' : `` xx '' , `` delivery_point '' : `` xx '' , `` delivery_point_check_digit '' : `` xx '' } , `` metadata '' : { `` record_type '' : `` S '' , `` zip_type '' : `` Standard '' , `` county_fips '' : `` 36047 '' , `` county_name '' : `` Kings '' , `` carrier_route '' : `` C009 '' , `` congressional_district '' : `` 11 '' , `` rdi '' : `` Residential '' , `` elot_sequence '' : `` 0070 '' , `` elot_sort '' : `` A '' , `` latitude '' : 40.6223 , `` longitude '' : -74.00717 , `` precision '' : `` Zip9 '' , `` time_zone '' : `` Eastern '' , `` utc_offset '' : -5 , `` dst '' : true } , `` analysis '' : { `` dpv_match_code '' : `` Y '' , `` dpv_footnotes '' : `` AABB '' , `` dpv_cmra '' : `` N '' , `` dpv_vacant '' : `` N '' , `` active '' : `` Y '' } } ] public void Main ( ) { try { var results = Client.Lookup ( Dts.Variables [ `` User : :authID '' ] .Value.ToString ( ) , Dts.Variables [ `` User : :ServiceAddress '' ] .Value.ToString ( ) , Dts.Variables [ `` User : :ServiceCity '' ] .Value.ToString ( ) , Dts.Variables [ `` User : :ServiceState '' ] .Value.ToString ( ) , Dts.Variables [ `` User : :ServiceZipCode '' ] .Value.ToString ( ) ) ; if ( results == null ) { throw new Exception ( `` Failed to get DPV for ServiceAddress '' ) ; } else { var DPV = results.analysis ; Dts.Variables [ `` User : :DPV '' ] .Value = DPV ; } } } catch ( Exception ex ) { Dts.Variables [ `` User : :DPV '' ] .Value = `` N '' ; throw ex ; } Dts.TaskResult = ( int ) ScriptResults.Success ; } public class Client { public static SmartyStreetsAddressLookup [ ] Lookup ( string authId = null , string street = null , string city = null , string state = null , string zip = null ) { try { using ( WebClient web = new WebClient ( ) ) { JsonSerializer serial = new JsonSerializer ( ) ; string response = web.DownloadString ( new Uri ( String.Format ( @ '' https : //us-street.api.smartystreets.com/street-address ? auth-id= { 0 } & street= { 1 } & city= { 2 } & state= { 3 } & zipcode= { 4 } '' , authId , street , city , state , zip ) ) ) ; return JsonConvert.DeserializeObject < SmartyStreetsAddressLookup [ ] > ( response ) ; } } catch ( Exception ex ) { throw ex ; } } } public class SmartyStreetsAddressLookup { public String [ ] metadata { get ; set ; } public String [ ] analysis { get ; set ; } } | API Call in C # using JSON |
C_sharp : If I have a routine that can throw an ArgumentException in two places , something like ... What ’ s the best way of determining in my calling procedure which of the two exceptions was thrown ? Or Am I doing this in the wrong fashion ? <code> if ( Var1 == null ) { throw new ArgumentException ( `` Var1 is null , this can not be ! `` ) ; } if ( Val2 == null ) { throw new ArgumentException ( `` Var2 is null , this can not be either ! `` ) ; } | Which of the two exceptions was called ? |
C_sharp : I 'll give a quick example of what I 'm familiar with implementing using C. The focus I think is on how the data can be used , not so much what I 'm doing with it in the example : ) So I 'm looking for advice on how similar data tables , or reference data , are implemented in C # . I 'm getting the hang of the higher level side of things , but I have n't dealt with any table driven data methods yet . As an example , what I might be trying to do in C # is to have a combo box allowing selection from the description field , while the colour id and quantity might be used to update read-only boxes . That 's a really simple example , but if I can determine a good way to implement that , I can extrapolate that to what I 'm actually doing . <code> typedef struct { const char *description ; uint32_t colour_id ; uint32_t quantity ; } my_data_t ; const my_data_t ref_data [ ] = { { `` Brown Bear '' , 0x88 , 10 } , { `` Blue Horse '' , 0x666 , 42 } , { `` Purple Cat '' , 123456 , 50 } , } ; void show_animals ( void ) { my_data_t *ptr ; ptr = & ref_data [ 2 ] ; console_write ( `` Animal : % s , Colour : 0x % 8X , Num : % d '' , ptr- > description , ptr- > colour_id , ptr- > quantity ) ; } | Coming from a C background , what 's a good way to implement const reference data tables/structures in C # ? |
C_sharp : From what I can piece together : int SalesTeamId is a variable and person is being assigned to the variable . After that I 'm lost . Any guidance ? <code> int salesTeamId = person == null ? -1 : person.SalesTeam.Id ; | Could someone interpret this line of code ? |
C_sharp : The MessageBox.Show call below shows `` Inner '' . Is this a bug ? <code> private void Throw ( ) { Invoke ( new Action ( ( ) = > { throw new Exception ( `` Outer '' , new Exception ( `` Inner '' ) ) ; } ) ) ; } private void button1_Click ( object sender , EventArgs e ) { try { Throw ( ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; // Shows `` Inner '' } } | Control.Invoke unwraps the outer exception and propagates the inner exception instead |
C_sharp : I 'm seeing some strange behavior when using a nullable long switch statement in VS2015 Update 1 that I 'm not seeing in other Visual Studio releases where it runs as expected.This sample code produces the following output ( Aligned for readability ) : I 'm only observing this behavior with Nullable types . Non-nullable types work as expected.Note that this is not the same behavior that 's in this question , and is not caused by this compiler bug that 's been fixed in VS2015 Update 1 . I 've verified that both of those examples run correctly . <code> class Program { static void Main ( string [ ] args ) { NullableTest ( -1 ) ; NullableTest ( 0 ) ; NullableTest ( 1 ) ; NullableTest ( 2 ) ; NullableTest ( null ) ; } public static void NullableTest ( long ? input ) { string switch1 ; switch ( input ) { case 0 : switch1 = `` 0 '' ; break ; case 1 : switch1 = `` 1 '' ; break ; default : switch1 = `` d '' ; break ; } string switch2 ; switch ( input ) { case -1 : switch2 = `` -1 '' ; break ; case 0 : switch2 = `` 0 '' ; break ; case 1 : switch2 = `` 1 '' ; break ; default : switch2 = `` d '' ; break ; } string ifElse ; if ( input == 0 ) { ifElse = `` 0 '' ; } else if ( input == 1 ) { ifElse = `` 1 '' ; } else { ifElse = `` d '' ; } Console.WriteLine ( `` Input = { 0 } , Switch 1 output = { 1 } , Switch 2 output = { 2 } , If Else = { 3 } '' , input , switch1 , switch2 , ifElse ) ; } Input = -1 , Switch 1 output = d , Switch 2 output = d , If Else = dInput = 0 , Switch 1 output = 0 , Switch 2 output = d , If Else = 0Input = 1 , Switch 1 output = d , Switch 2 output = d , If Else = 1Input = 2 , Switch 1 output = d , Switch 2 output = d , If Else = dInput = , Switch 1 output = d , Switch 2 output = d , If Else = d | Nullable Long switch statement not producing expected output in VS2015 |
C_sharp : What are the rules when resolving variable number of parameters passed by params ? Suppose , that I have the code : How is Method ( a , b , c ) resolved , if a is a IMyInterface ? Can I be sure , that C # will always try to select most matching overload ? <code> public void Method ( params object [ ] objects ) { } public void Method ( IMyInterface intf , params object [ ] objects ) { } | Resolving params in C # |
C_sharp : In C # , the following method will not compile : The compiler errors : 'IsItTrue ( ) ' : not all code paths return a value , which makes perfect sense . But the following compile without any issue . Which looks wrong as no return statement at all . Why is it so ? Any help here ... , <code> public bool IsItTrue ( ) { } public bool IsItTrue ( ) { while ( true ) { } } | Why compiler behaves differently with this code ? |
C_sharp : I 've built a method that returns me an instance of attribute if it is found on the property : In order to get instance , I have to invoke : And it works fine , I get exact instance of the attribute class.However , I do n't like that I have to use new NullableAttribute ( ) as parameter , I 'd like to have invoke look like : This however does not work due to the fact that as soon as I remove second parameter and add 1 generic type in method name , it starts to require other two as well . Is there a way to force the method to infer 2 out of 3 generic parameters ? I.e . I want to specify attribute class , but do n't want to specify class name and property name.UPDATE : Here 's the implemented code , thanks to Jon , as well as the code for string solution . I 've decided to nest the class so that I do n't polute the namespace if I introduce same approach for some other extension classes.So invoke now goes like this : <code> public static U GetPropertyAttribute < T , TProperty , U > ( this T instance , Expression < Func < T , TProperty > > propertySelector , U attribute ) where U : Attribute { return Attribute.GetCustomAttribute ( instance.GetType ( ) .GetProperty ( ( propertySelector.Body as MemberExpression ) .Member.Name ) , typeof ( U ) , true ) as U ; } var cc = new CustomClass ( ) ; cc.GetPropertyAttribute ( x = > x.Name , new NullableAttribute ( ) ) cc.GetPropertyAttribute < NullableAttribute > ( x = > x.Name ) public static class AttributeExtensions { public static ObjectProperty < T , TProperty > From < T , TProperty > ( this T instance , Expression < Func < T , TProperty > > propertySelector ) { return new ObjectProperty < T , TProperty > ( instance , propertySelector ) ; } public class ObjectProperty < T , TProperty > { private readonly T instance ; private readonly Expression < Func < T , TProperty > > propertySelector ; public ObjectProperty ( T instance , Expression < Func < T , TProperty > > propertySelector ) { this.instance = instance ; this.propertySelector = propertySelector ; } public U GetAttribute < U > ( ) where U : Attribute { return Attribute.GetCustomAttribute ( instance.GetType ( ) .GetProperty ( ( propertySelector.Body as MemberExpression ) .Member.Name ) , typeof ( U ) , true ) as U ; } } public static T GetPropertyAttribute < T > ( this object instance , string propertyName ) where T : Attribute { return Attribute.GetCustomAttribute ( instance.GetType ( ) .GetProperty ( propertyName ) , typeof ( T ) , true ) as T ; } } var cc = new CustomClass ( ) ; var attr = cc.From ( x = > x.Name ) .GetAttribute < NullableAttribute > ( ) ; | Inferring 2 out of 3 generic types |
C_sharp : I was just wondering if a simple static function using the ? : operator is inlined during just in time compilation . Here is an arbitrary example using the code.Which gives the following IL : Or would the simplier alternative be inlined ? Here is the IL for it : The ? : operator apparently generates a more concise MSIL than the if alternative , but does anyone know what happens during JIT compilation ? Are both of them inlined ? Are either of them inlined ? <code> public static int Max ( int value , int max ) { return value > max ? max : value ; } Max : IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.1 IL_0003 : bgt.s IL_0008IL_0005 : ldarg.0 IL_0006 : br.s IL_0009IL_0008 : ldarg.1 IL_0009 : stloc.0 IL_000A : br.s IL_000CIL_000C : ldloc.0 IL_000D : ret public static int Max ( int value , int max ) { if ( value > max ) { return max ; } else { return value ; } } Max : IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.1 IL_0003 : cgt IL_0005 : stloc.0 IL_0006 : ldloc.0 IL_0007 : brfalse.s IL_000EIL_0009 : nop IL_000A : ldarg.1 IL_000B : stloc.1 IL_000C : br.s IL_0013IL_000E : nop IL_000F : ldarg.0 IL_0010 : stloc.1 IL_0011 : br.s IL_0013IL_0013 : ldloc.1 IL_0014 : ret | Are Methods using the ? : Operator Inlined during JIT compilation ? |
C_sharp : I need an accurate searching function whether in jquery or c # . If possible I want the searching as brilliant as google : - ) So here is c # code : Brief explanation : This searches all users in database that has complete information . It searches all users except the currently logged in user . And the result : The encircled name must be on the top of the search items since it matches more keyword.Any idea ? <code> string [ ] ck = keyword.Split ( new string [ ] { `` `` , `` , '' , `` . '' } , StringSplitOptions.RemoveEmptyEntries ) ; using ( dbasecore db = ConfigAndResourceComponent.BaseCampContext ( ) ) { var results = ( from u in db.users join uinfo in db.userinfoes on u.UserID equals uinfo.UserID where u.UserID ! = userid & & ( ck.Contains ( u.LastName ) || ck.Contains ( u.FirstName ) || ck.Contains ( u.MiddleName ) || ck.Contains ( u.LoginID ) ) orderby u.LastName , u.FirstName , u.MiddleName ascending select uinfo ) .Skip ( skip ) .Take ( take ) .ToList ( ) ; return ( from i in results select new UserInfo ( i ) ) .ToList ( ) ; } | How to create more accurate searching ? |
C_sharp : I 'm looking to understand a bit more about LINQ and use it a little more , so a little bit of self development work going here ... I have an object as follows : Now , given a list of players , I 'd like to select the ones that have formerly played for various selected clubs , I could do it easily by a couple of foreach statements nested - but I 'd like to do it with Linq ... I 've tried this , but nothing is returned from it : Any help in where I 'm going wrong ? The data definitely exists because when I have a foreach loop looping over the clubs inside a loop which loops over the players and I return a collection of all players who 've played for clubs 1,2 & 3 there is data ... Effectively it should return several instances of a HistoryOfPlayer object , all containing the names of the same 3 clubs ( given they 're linked on ID ) - as I say , its a bit of self learning , so trying to apply it to sport so it sticks in my head a bit ! ! Can someone help out ? <code> public class Player ( ) { public string Name { get ; set ; } public Club currentClub { get ; set ; } public IEnumerable < Club > previousClubs { get ; set ; } } var prevClubs = from player in players from clubOriginal in player.previousClubs from clubSecond in player.previousClubs from clubThird in player.previousClubs where clubOriginal.ID == 1 where clubSecond.ID == 2 where clubThird.ID == 3 select new HistoryOfPlayer { firstClub == clubOriginal.Name , secondClub == clubSecond.Name , thirdClub == clubThird.Name } | Object population with LINQ |
C_sharp : I ca n't figure it out , where did I go wrong ? I got the following datetime string , and need to parse it to datetime : And I trying to parse it like this : When trying to do this it returns `` string was not recognized as a valid DateTime '' Any tip ? <code> string timestr = `` 1/20/2014 12:05:16 AM '' DateTime.ParseExact ( timestr , `` MM/dd/yyyy hh : mm : ss tt '' , null ) ; | How can I parse this datetime string ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.