简体   繁体   中英

trouble converting function from vb to c#

I am trying to migrate myself to only using C# (was/am a vb.net guy) I am having trouble converting this vb.net function from a project Im migrating to C#

Public Shared Function GetHolidays(ByVal holidaysFile As String) As List(Of Date)
    Dim sAllDates() As String = File.ReadAllLines(holidaysFile)
    Return (From sDate In sAllDates Select CDate(sDate)).ToList()
End Function

holidaysFile is a text file that contains items like this;

01/01/2015 01/19/2015 02/16/2015 04/03/2015 05/25/2015 07/03/2015 09/07/2015 11/26/2015 12/25/2015

any help appreciated, and streamreader may be better way to read this?

You can do

public static List<DateTime> GetHolidays(string holidaysFile)
{
    string[] sAllDates = File.ReadAllLines(holidaysFile);
    return (from sDate in sAllDates select Convert.ToDateTime(sDate)).ToList();
}

This matches the original:

public static List<DateTime> GetHolidays(string holidaysFile)
{
    return File.ReadAllLines(holidaysFile).Select(d => Convert.ToDateTime(d)).ToList();
}

But it kills me to use a List like that unless there's a real need for it. The code below will allow you to do lazy evaluation, supports only keeping one line in RAM at a time, and often still works with no changes to the calling code — many of the same benefits as using a StreamReader. Note that it's also shorter, and can still be easily converted to a List if needed. While I'm here, since you're coming from a string, you might do better using the DateTime.Parse() method:

public static IEnumerable<DateTime> GetHolidays(string holidaysFile)
{
    return File.ReadLines(holidaysFile).Select(d => DateTime.Parse(d));
}

As a general rule, you're almost always better off writing code to return an IEnumerable<T> instead of a List<T> . You have very little to lose, because you can always just append .ToList() to the end of such a function when you need, and much to gain in terms of easier refactoring from one underlying collection type to another and potential performance improvements by reducing RAM use or avoiding looping over items in the List it later turns out you never needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM