HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Retrieving a csv header

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
retrievingcsvheader

Problem

I have two seperate calls that returns a .csv file. I need to extract a couple of headers from the files depending on which one is called. The headers does not always sit in the same index, and the CourseId name changes to Asset_ID in the one call.

How can I refactor the code to make it more maintainable?

Also, I think the naming is not really good.

public static class CsvHeader
        {
            public struct Index
            {
                public string Email { get; set; }
                public string CompletionDate { get; set; }
                public string CourseId { get; set; }
            }
            public static Index GetCsvHeaderIndex(string[] headers)
            {
                string emailIndex = null;
                string completionDateIndex = null;

                var email = headers.FirstOrDefault(_ => _.Contains("Email"));
                var completionDate = headers.FirstOrDefault(_ => _.Contains("Completion"));
                var courseId = headers.FirstOrDefault(_ => _.Contains("CourseID"));

                if (!string.IsNullOrEmpty(email)) emailIndex = headers.First(_ => _.Contains("Email")).Split('(', ')')[1]; /*3*/
                if (!string.IsNullOrEmpty(completionDate)) completionDateIndex = headers.First(_ => _.Contains("Completion")).Split('(', ')')[1]; /*30*/
                var courseIdIndex = string.IsNullOrEmpty(courseId) ? 
                    headers.First(_ => _.Contains("Asset_ID")).Split('(', ')')[1] : 
                    headers.First(_ => _.Contains("CourseID")).Split('(', ')')[1];

                return new Index
                {
                    Email = emailIndex,
                    CompletionDate = completionDateIndex,
                    CourseId = courseIdIndex
                };
            }
        }

Solution

-
Kudos for creating a struct to strong type the data, but what does Index mean? It's an odd term for course information. I'd look for a better name.

-
Also, don't string type all the things. You have a date here, you should store it as a date.

public string CompletionDate { get; set; }


MSDN article on parsing dates from strings.

-
You're duplicating string literals like "Email". Extract constants for these.

-
You're splitting on the same character array in several places, but recreating the array for each call. Extract a local variable for ['(', ')']

Code Snippets

public string CompletionDate { get; set; }

Context

StackExchange Code Review Q#114267, answer score: 12

Revisions (0)

No revisions yet.