C# Newbie needs help: convert enum to string - c#

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.

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.

find string from enum

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.

C# pass enum "name" and enum value to method

I'm doing Einstein-Riddle in C# atm and stubled across a problem.
I'm trying to do it with enums.
I have a struct called House. In House there are enums like Nationality, Color, Animal, ...
I create every possible solution in House and want to delete things with the hints (in a separate method).
Hint #1: British lives in red house.
Now I have to pass Nationality as enum and Nationality.British as value & Color as enum and Color.Red as value.
How to do this? I just want to call my Method like -
CheckLine(Nationality.British, Color.Red);
but what to put in parameter-list:
static void CheckLine( ? )
Here's my struct and enums
public enum Nationalitaet { Däne, Brite, Deutscher, Norweger, Schwede };
public enum Farbe { rot, blau, grün, weiß, gelb };
public enum Zigarette { Dunhill, Marlboro, PallMall, Rothmans, Wingfield };
public enum Tier { Pferd, Fisch, Katze, Vogel, Hund };
public enum Getraenk { Wasser, Kaffee, Milch, Tee, Bier };
struct Haus
{
public int HausNr { get; set; }
public Nationalitaet Nationalitaet { get; set; }
public Farbe Farbe { get; set; }
public Zigarette Zigarette { get; set; }
public Tier Tier { get; set; }
public Getraenk Getraenk { get; set; }
}
I've a List with all solutions (called solution)
in CheckLine there's
if (solution[i].Nationalitaet == Nationalitaet.British && solution[i].Farbe == Farbe.Red)
solution.RemoveAt(i)```
The correct signature would be:
static void CheckLine(Nationality nationality, Color color) { }
An enum type (e.g. Nationality) can be used just like any other type, similar to how you would use int or string.
The names of the parameters (nationality, color) are of course free to choose, but generally speaking the most appropriate name for them matches the name of the enum type itself.
There is not enough information in the question to judge whether it should be static or not, or whether the method should or should not return a void. This answer only focuses on the input parameters of the method.

How to set two values for same definition in enum, C#

I am trying to compare values that I am getting from web service, but sometimes I get int value, sometimes i get string. So it would be great that i could only check for Type.value1.
for example:
enum Type { value1 = 1 , value1="one"}
and like that for more value2, etc...
But of course, I cannot do this because it I cannot add two definitons for value1.
Sometimes a type that behaves mostly like an enum but has some richer behaviour can be very useful:
public sealed class MyFakeEnum {
private MyFakeEnum(int value, string description) {
Value = value;
Description = description;
}
public int Value { get; private set; }
public string Description { get; private set; }
// Probably add equality and GetHashCode implementations too.
public readonly static MyFakeEnum Value1 = new MyFakeEnum(1, "value1");
public readonly static MyFakeEnum Value2 = new MyFakeEnum(2, "value2");
}
You can consider adding attributes to the enums and use reflection.
enum Type
{
[Description("One")]
value1 = 1
}
I also make use of using decorating the enum with a description attribute as described by BSoD_ZA. But I would suggest that you then implement an extension method for the enumeration to obtain the string description for example:
public static class EnumExtension
{
public static string ToDescription<TEnum>(this TEnum enumValue) where TEnum : struct
{
return ReflectionService.GetClassAttribute<DescriptionAttribute>(enumValue);
}
}
enum Type
{
[Description("One")]
value1 = 1
}
var value = Type.Value1;
Console.Writeline(value.ToDescription());

Problem in sort by date in multi array?

I want to sort array A based on values in Array B
actually in Array A I have topics like
keyboard
Laptop
Desktop
mouse
and in Array B i have dates associated with each value in Array A
how i can achieve this....I was thinking of using multi array but i m not sure if there is any default method of sorting multi array ...or if there is any other method to achieve this?
Use:
Array.Sort (A, B, comparer); // comparer can be null here to use the default
where A is the DateTime [] and B is the string [] with A[0] being the date that corresponds to the string B[0] and so on. (MSDN docs here)
Create an object with two properties: a string for your topic and a datetime for your dates. Place those objects in an array or collection and you can then sort on the date and choose to project an array of your topics if you so desire.
If you are managing this completely, you might want to put these into a single class:
class HardwareElement
{
public HardwareElement(string topic, DateTime date)
{
this.Topic = topic;
this.Date = date;
}
public string Topic { get; set; }
public DateTime Date { get; set; }
}
Then, given an array of the above, you can sort these easily:
HardwareElement[] theArray = PopulateMyArray();
Array.Sort(theArray, (l, r) => l.Date.CompareTo(r.Date));
Unless you have a specific reason, you probably shouldn't be storing two associated pieces of data in completely separate arrays.
you could possibly try something like the following:
public enum Device
{
Laptop,
Mouse,
Keyboard
}
public struct DeviceEvent
{
public DeviceEvent(Device device, DateTime timestamp) : this()
{
Device = device;
TimeStamp = timestamp;
}
public Device Device { get; set; }
public DateTime TimeStamp { get; set; }
}
List<DeviceEvent> deviceEvents = new List<DeviceEvent>();
deviceEvents.Add(new DeviceEvent(Device.Keyboard, DateTime.Now);
deviceEvents.Add(new DeviceEvent(Device.Mouse, DateTime.Today);
... etc
IEnumerable<DeviceEvent> orderedDeviceEvents = deviceEvents.OrderBy(e = > e.TimeStamp);

Categories