This question already has answers here:
How do I convert an enum to a list in C#? [duplicate]
(14 answers)
Closed 9 years ago.
Here's a "weird" question:
Is it possible to create a method where in it will convert whatever enum to list. Here's my draft of what I'm currently thinking.
public class EnumTypes
{
public enum Enum1
{
Enum1_Choice1 = 1,
Enum1_Choice2 = 2
}
public enum Enum2
{
Enum2_Choice1 = 1,
Enum2_Choice2 = 2
}
public List<string> ExportEnumToList(<enum choice> enumName)
{
List<string> enumList = new List<string>();
//TODO: Do something here which I don't know how to do it.
return enumList;
}
}
Just curious if it's possible and how to do it.
Enum.GetNames( typeof(EnumType) ).ToList()
http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx
Or, if you want to get fancy:
public static List<string> GetEnumList<T>()
{
// validate that T is in fact an enum
if (!typeof(T).IsEnum)
{
throw new InvalidOperationException();
}
return Enum.GetNames(typeof(T)).ToList();
}
// usage:
var list = GetEnumList<EnumType>();
public List<string> ExportEnumToList(<enum choice> enumName) {
List<string> enumList = new List<string>();
//TODO: Do something here which I don't know how to do it.
foreach (YourEnum item in Enum.GetValues(typeof(YourEnum ))){
enumList.Add(item);
}
return enumList;
}
Related
This question already has answers here:
Difference between a List's Add and Append method?
(2 answers)
Closed 4 months ago.
https://dotnetfiddle.net/QHd0Rr#
I'm trying to populate a simple IEnumerable but I'm getting an error:
Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Program.Main()
Command terminated by signal 6
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var key1 = new WidgetA{Id = 1, Key = 52};
var key2 = new WidgetA{Id = 1, Key = 102};
var key3 = new WidgetA{Id = 1, Key = 152};
IEnumerable<WidgetA> list = Enumerable.Empty<WidgetA>();
list.Append(key1);
list.Append(key2);
list.Append(key3);
Console.WriteLine(list.ToList()[0]);
}
}
public class WidgetA
{
public int Id { get; set; }
public int Key { get; set; }
public string ValueToGet { get; set; }
}
Enumerable.Append<> is a lazy Linq function. If this is how you want to use it, you need to store the intermediate result:
IEnumerable<WidgetA> list = Enumerable.Empty<WidgetA>();
list = list.Append(key1);
list = list.Append(key2);
list = list.Append(key3);
While I really like (and upvoted) Blindy's answer and I think that it may better fit your need, here is an alternative with yield return:
public static void Main()
{
IEnumerable<int> list = DoStuff();
list.Dump();
}
public static IEnumerable<int> DoStuff()
{
yield return 0;
yield return 1;
// enter code here or whatever
yield return 2;
yield return 3;
yield return 4;
}
This question already has answers here:
Both c# lists being modified
(6 answers)
Closed 1 year ago.
I wanted to initialize my class with the list of ints for example:
{1,5,6,7,1,0} and then modify them and get two fields, one with the same list of ints and the second with a modified list of ints. But as a result, I get two modified lists with values: {0,4,5,6,0,0}. Can someone explain to me why this code acts like this?
MyClass
public class MyClass
{
public List<int> numbers { get; }
public List<int> diffrentNum { get; set; }
public MyClass(List<int> _numbers)
{
numbers = _numbers;
diffrentNum = GetNumbers();
}
private List<int> GetNumbers()
{
List<int> localNumbers = numbers;
for (int i=0;i<localNumbers.Count-1;i++)
{
if (localNumbers[i] > 0)
{
localNumbers[i]--;
}
}
return localNumbers;
}
}
Main
static void Main(string[] args)
{
List<int> someDate = new List<int>();
someDate.Add(1);
someDate.Add(5);
someDate.Add(6);
someDate.Add(7);
someDate.Add(1);
someDate.Add(0);
MyClass myclass= new MyClass(someDate);
Console.WriteLine(String.Join("", new List<int>(someDate).ConvertAll(i => i.ToString()).ToArray()));
Console.WriteLine(String.Join("", new List<int>(myclass.numbers).ConvertAll(i => i.ToString()).ToArray()));
Console.WriteLine(String.Join("", new List<int>(myclass.diffrentNum).ConvertAll(i => i.ToString()).ToArray()));
Console.ReadKey();
}
By calling List<int> localNumbers = numbers; you're assigning both variables to point to the same object, so any changes made through one of them are visible through the other.
One way to create a copy of a list is by using Linq's ToList:
List<int> localNumbers = numbers.ToList();
This question already has answers here:
Get array from C# string property
(3 answers)
Closed 3 years ago.
Data incoming from a SQL Server has a field with a pipe delimited string IE:
20190819|20190830|20190915
I would like my Class property to return a string[]. I can manually do it with split, but I want my class property to perform the calculation and conversion.
/* Use MyObject like below:
var b = new MyObject();
b.datesString = "20190819|20190830|20190915"; //set datesList to list of strings
var ss = new List<string> { "a", "b" };
b.datesList = ss; //set datesString to 'a|b'
*/
public class MyObject {
public string datesString {get;set;}
public IEnumerable<string> datesList
{
get
{
if(string.IsNullOrEmpty(datesString))
{
return null;// or new empty list
}
return datesString.Split('|');
}
set
{
if(value != null)
{
datesString = "";
foreach(var s in value)
{
datesString += s + "|";
}
datesString = datesString.Substring(0, datesString.Length - 1);
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have following class with three properties.
public class Item
{
public float a { get; set; }
public float b { get; set; }
public float c { get; set; }
}
Below is the method where I need a return type of class Item which should not contain the default or null value. How can I achieve this.
class Program
{
static void Main(string[] args)
{
List<Item> callingprogram = CallIngprogram1();
callingprogram2(callingprogram);
}
private static List<Item> callingprogram2(List<Item> paramss )
{
if (paramss[0].c == 0.0)
{
// return the list which should not contain the property C. IF the value is null or default value that property value should not return
}
return null;
}
private static List<Item> CallIngprogram1()
{
List<Item> list = new List<Item>();
list.Add(new Item
{
a = 1,
b = 3
// c value is not assign so it contain the default value
});
return list;
}
}
Suppose I assign a value to all the three property all three property should return. If I don't assign any value to any of the property name as well as value should not return.
The default value of float in c# is 0. You can put this logic in your callingprogram2(). If all values are assigned it will return a,b,c and if c is not assigned it will return a,b:
EDIT:
private static List<dynamic> callingprogram2(List<Item> paramss)
{
dynamic newList = new List<dynamic>();
foreach (var item in paramss)
{
dynamic dObject = new ExpandoObject();
dObject.a = item.a;
dObject.b = item.b;
if (item.c != 0.0)
{
dObject.c = item.c;
}
newList.Add(dObject);
}
return newList;
}
Until you defined a class, any instance of it will contains all the properties. The question is how do you use this instance. May be you need to change the logic that uses instances.
This question already has answers here:
How to get the type of T from a member of a generic class or method
(17 answers)
Closed 9 years ago.
I need get a type of list element.
using System;
using System.Collections;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var xClass = new XClass();
xClass.Do();
}
}
public class XClass
{
public List<string> list1 = new List<string>();
public List<string> list2 { get; set; }
public void Do()
{
// first
Console.WriteLine("Type = {0}", GetListType(list1));
// second
var propertyList = this.GetType().GetProperty("list2"); // i get list from reflection
// Create instance of list2
var newList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(propertyList.PropertyType)));
Console.WriteLine("Type = {0}", GetListType(newList));
}
private Type GetListType(IEnumerable list)
{
return list.GetType().GetGenericArguments()[0];
}
}
Output:
Type = System.String
Type = System.Collections.Generic.List`1[System.String]
I need to get "System.String" in second case
You can test code here http://ideone.com/uLkfBx
The statement var newList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(propertyList.PropertyType))); creates an instance of a generic List that contains the type of list2. So newList is of type List<List<string>> hence your result is correct.