find string from enum - c#

I have tried to below suggestions but nothing works, and I have edited the code to be easier.
the purpose of this code is to get the row of the data based on the enum.
For example: if I give the value "bra" for search, then the wanted result should be brazil from enum but since the enum is an int then it's like I'm saying select the data where location = 3 if we suppose that brazil =3 in the enum.
public LocationType Location { get; set; }
public enum LocationType
{
brazil,
USA,
UK
}
public async Task<IActionResult> Index(string id, [FromForm] string search)
if (!string.IsNullOrWhiteSpace(search))
{
result = applicationDbContext.Where(x => x.Location.ToString().Contains(search)).ToList();
}
note: search is string input.

If you want to get the numeric values (or enum values) of those that matches the search you can do it like below:
public async Task<IActionResult> Index(string id, [FromForm] string search)
if (!string.IsNullOrWhiteSpace(search))
{
List<LocationType> locations = Enum.GetNames(typeof(LocationType))
.Where(x => x.ToLower().Contains(search.ToLower()))
.Select(x => Enum.Parse<LocationType>(x))
.ToList();
result = applicationDbContext.Where(x => locations.Contains(x.Location)).ToList();
}

Converting your Enum to string:
Location.ToString(); //output = A
But This converts your Enum to a string containing all members:
string[] locs= Enum.GetNames(typeof(LocationType ));
which can be used in your query.

(char)locs does definitly not what you expect it does. An enum is nothing but an int, and thus it can be directly converted to a char. But (char)1 is not the letter A, but an ASCII-control-code. The letter A has the code 65, though.
So you have a couple of opportunities:
make your enum start at 65:
public enum LocationType
{
A = 65,
B = 66,
C = 67,
K = 75
}
Now when you convert the enum to char you´d get A for example.
Use enum.ToString(), e.g. LocationType.C.ToString() returns "C".
The better idea however is to use the built-in functionality to get an enums name as m.r226 pointed out in his answer.

Related

Best way generate XML with an enum's values and descriptions in C#

I have to send string with xml containing enums serialized to xml.
Those enums are in nuget package, so I can't edit them.
All enums have name, value and description attribute.
public enum FileExtenstion
[Description("XML extension")]
xml = 1,
[Description("TXT extension")]
txt = 2
end enum
My function to get xml from this enum looks like this:
public static string GetFileExtension()
{
var _cache = System.Enum.GetValues(typeof(FileExtension))
.Cast<FileExtension>()
.Select(enumValue => new EnumToXmlSerializer
{
Name = enumValue.ToString(),
Value = (int)enumValue,
Description = enumValue.GetDescription()
}).ToList();
(...)
}
public class EnumToXmlSerializer
{
public string Name { get; set; }
public int Value { get; set; }
public string Description { get; set; }
}
Works well.
But I have a lot of enums to convert and better way will be to prepare some parametrized function with convert string with name of enum ("FileExtension") to type.
I haven't idea how to convert enum name (not enum every value name but enum type name) and convert its to type. In stackoverflow I found only conversion for enum values not all types.
I'm looking for solution to prepare function like this:
public string GetXmlFromEnumTypeName("FileExtension")
to get:
<enums>
<enum><name>xml</name><value>1</value><description>XML extension</description></enum>
<enum><name>txt</name><value>2</value><description>TXT extension</description></enum>
</enums>
I suppose there will be one line to change my GetFileExtension function but I usually get it wrong about things like that.

Is there a way to read a txt file into a list without using List<String>?

I am trying to read a .txt file into a list without using a List<string> type. I have created a separate class, called Club, that does all of the sorting. However, I am having difficulties actually reading in the .txt file.
string path = "C:\\Users\\Clubs-2019";
public List<Club> ReadClubsTxtFile()
{
List<Club> outcome = new List<Club>();
string[] text = File.ReadAllLines(path);
outcome.Add(text);
return outcome;
}
The line outcome.Add(text); shows an error as I am trying to send the wrong type to the list.
This is a sample of the text file:
Club Name Club Number Meeting Address Latitude Longitude Meeting Day Meeting Time Meeting End Time
Alabaster-Pelham 4018 1000 1st St North Alabaster AL 35007 33.252414 -86.813044 Thursday 12:15 PM 1:15 PM
Albertville 4019 860 Country Club Road Albertville AL 35951 34.296807 -86.198587 Tuesday 12:00 PM 1:00 PM
Alexander City 29375 16 Broad St. Alexander City AL 35010 32.945387 -85.953948 Monday 12:00 PM 1:00 PM
The "Clubs" Class is shown below.
public Club(string name, ClubTypes type, long idNumber, RecurrableMeeting regularMeeting = null, RecurrableMeeting boardMeeting = null, List<IndividualMeeting> otherMeetings = null)
{
this.name = name;
this.type = type;
this.idNumber = idNumber;
this.regularMeeting = regularMeeting;
this.boardMeeting = boardMeeting;
this.otherMeetings = otherMeetings;
if (this.otherMeetings == null)
this.otherMeetings = new List<IndividualMeeting>();
}
"The line "outcome.Add(text); " shows an error as I am trying to send the wrong type to the list."
The reason for this error is that you're trying to add a string[] to a list that contains Club. What we need is a method that will take a string and return a Club, and then we can call that method on each file line before adding to the list.
A common way to do this is to add a Parse method to the Club class that can create an instance of the class from a string.
A complete example could be provided if you shared some sample lines from the text file (typically these would map to properties of the class) and the definition of the Club class. However, here is a sample that you can hopefully apply to your specific situation.
First, example lines in a text file:
1,Ravens,10/10/2019,2
2,Lions,05/25/2019,5.7
3,Tigers,09/12/2018,6.2
4,Bears,11/05/2019,9.1
5,Wildcats,03/04/2017,4.8
And the definition of Club
public class Club
{
public int Id {get; set;}
public string Name {get; set;}
public DateTime FoundedOn {get; set;}
public double Score {get; set;}
}
As you can see, the lines in the text file map to properties of the Club class. Now we just need to add a static method to the Club class that returns an instance of the class based on a line of text from the file.
The idea is that we split the line on the comma character, convert each part to the correct data type for the property, set the properties, and return the class. We need to validate things like:
The line is not null
The line contains the correct number of parts
Each part is the correct datatype
In the case of a validation failure, we have some common choices:
Throw an exception
Return null
Return a partially populated class
In the sample below I'm returning null to indicate bad data, mostly because it makes parsing the file easier.
Here's the class with the Parse method added:
public class Club
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime FoundedOn { get; set; }
public double Score { get; set; }
public static Club Parse(string input)
{
// Try to split the string on the comma and
// validate the result is not null and has 4 parts
var parts = input?.Split(',');
if (parts?.Length != 4) return null;
// Strongly typed variables to hold parsed values
int id;
string name = parts[1].Trim();
DateTime founded;
double score;
// Validate the parts of the string
if (!int.TryParse(parts[0], out id)) return null;
if (name.Length == 0) return null;
if (!DateTime.TryParse(parts[2], out founded)) return null;
if (!double.TryParse(parts[3], out score)) return null;
// Everything is ok, so return a Club instance with properties set
return new Club {Id = id, Name = name, FoundedOn = founded, Score = score};
}
}
Now that we have the parse method, we can create a List<Club> from the text file quite easily:
public static List<Club> ReadClubsTxtFile(string path)
{
return File.ReadAllLines(path).Select(Club.Parse).ToList();
}
You could do something like this:
string path = "C:\\Users\\Clubs-2019";
public List<Club> ReadClubsTxtFile()
{
return File.ReadAllLines(path)
.Select( line => new Club {SomeProperty = line} )
.ToList();
}

Search in list of strings by name of the string

I have the following list I'm populating as I go through my class:
List<string> stringCollection = new List<string>();
I have a lot of static strings that I have declared before going to my class.
These strings are added to my list based on a collection of conditional expressions, meaning that it varies what kind of strings that I put into my list e.g.:
static string DescriptionText1 = "blabla",
DescriptionText2 = "blabla",
MagnitudeText1 = "blabla",
MagnitudeText2 = "blabla";
if(number < 2)
{
stringcollection.Add(DescriptionText1)
}
else
{
stringcollection.Add(DescriptionText2)
}
//Magnitude
if(magnitude > 128 && number < 256)
{
stringcollection.Add(MagnitudeText1)
}
else
{
stringcollection.Add(MagnitudeText2)
}
...
I then pass the list to my method in which I want to retrieve the strings like so:
public void Collection(List<string> ts)
{
string Description = ts.Find(DescriptionText); <--- my guess
string Magnitude = ts.Find(MagnitudeText);
}
How do I find the correct strings in my list, and write it to my newly declared strings in my method? - Even though they are appended hence 1,2,3 ... 6,7
Since you always put in Description first and then Magnitude, you can just do:
ts[0] // description
ts[1] // magnitude
Alternatively, consider writing a class that has the two properties:
// I don't know what these two things represent, please name it properly in your code!
class DescriptionMagnitude {
public string Description { get; }
public string Magnitude { get; }
public DescriptionMagnitude(string description, string magnitude) {
Description = description;
Magnitude = magnitude;
}
}
And then create an instance of this class and pass it around.
EDIT:
From your comment:
and then i would be able to search for my int variable?
It seems like you want to find the integer associated with the string. However, the 1 in DescriptionText1 is just part of an identifier. Why not just store the integer instead of the string?
Depending on what you are doing with the strings, an enum may be suitable:
enum Descriptions {
Foo = 0,
Bar = 1
Fizz = 2
}

How to return values from Entity Framework with parameters based on a bitwise Enum

Bit (sorry) confused about how to use bitwise operators with Entity Framework.
A recent requirement has necessetated that we alter an enum from a series of sequential integers into a bitwise enum. So:
[Flags]
public enum AdminLevel
{
None = 0,
Basic = 1,
Partial = 2,
Full = 4
}
We originally stored this as an int column in the database. It's still an int, of course, but I'm having trouble seeing how I can perform selections based on more than one possible enum value. For example this code:
public string GetAdminEmails(AdminLevel adminlevel)
{
using (IRepository r = Rep.Renew())
{
string[] to = r.GetUsers().Where(u => u.AdminLevel >= (int)adminlevel).Select(u => u.Email).ToArray();
return string.Join(",", to);
}
}
Would return all the admin levels including and above the one supplied. If I want more than one admin level, I now have to call it like this:
GetAdminEmails(AdminLevel.Partial | AdminLevel.Full);
But obviously I can't convert that to an int and use greater than any more. Is there a neater way of handling this change than a series of flow control statements?
You can use the HasFlag method:
AdminLevel myFlags = AdminLevel.Partial | AdminLevel.Full;
string s = GetAdminEmails(myFlags);
public string GetAdminEmails(AdminLevel myFlags)
{
using (IRepository r = Rep.Renew())
{
string[] to = r.GetUsers().Where(u => u.AdminLevel.HasFlag(myFlags))
.Select(u => u.Email).ToArray();
return string.Join(",", to);
}
}
You can define an int column in your database as an enumeration in your model:
public enum MyEnum : int { First = 0, Second = 1}
public partial class MyModel
{
public MyEnum Type {get; set;}
}
Throughout your application you can just use MyEnum and EF will work with int on the background.

C# Newbie needs help: convert enum to string

I am a programming novice. I would like to convert ComputerHand and PlayerHand to strings so I can then create an string array to write to a text file.
public enum Hand { Rock = 1, Paper, Scissors };
public enum Outcome { Win, Lose, Tie };
public Hand ComputerHand { get; set; }
public Hand PlayerHand { get; set; }
public char UserSelection { get; set; }
Given below Enum,
public enum AnEnum
{
Value1,
Value2,
Value3
}
Short answer: AnEnum.Value1.ToString()
If you want to give a different details (friendlier string) to enum value, you can use "Description" attribute to enum. See this: How can I assign a string to an enum instead of an integer value in C#?
If you are dealing with enum <-> string, you may sometime want to convert string to an enum, which can be done like this:
AnEnum AnEnumValue = (AnEnum ) Enum.Parse(typeof(AnEnum ), "Value1", true);
Just for someone's benefit who is working with enum ans strings, if you want to make an array of string from enum values,
string[] arrayOfEnumStrings
= Enum.GetValues(typeof(AnEnum)).Cast<AnEnum>()
.Select(enumVal=> enumVal.ToString()).ToArray();
Here, "Enum.GetValues(typeof(Foos)).Cast()" will get you enumurator of enum values. Then "Select" will convert those enum values to string.

Categories