Generate random number from two List<> - c#

i want to generate random number from two list. i want to create a function where i pass how much random number from two list.
List<int> integers = new List<int>() { 54, 23, 76, 123, 93, 7, 3489 };
List<int> value2 = new List<int>() { 1, 3, 4, 6, 8, 17, 40 };
i want my result = List<int> result = {54,40,123,17,3,1,3489,76...etc}
When i run again the set of result will be change.
Presently i am using this function that return List
public static List<int> GenerateRandom(int count)
{
// generate count random values.
HashSet<int> candidates = new HashSet<int>();
while (candidates.Count < count)
{
// May strike a duplicate.
candidates.Add(random.Next(1,30));
}
// load them in to a list.
List<int> result = new List<int>();
result.AddRange(candidates);
// shuffle the results:
int i = result.Count;
while (i > 1)
{
i--;
int k = random.Next(i + 1);
int value = result[k];
result[k] = result[i];
result[i] = value;
}
return result;
}
i am calling the function
List<int> vals = GenerateRandom(20);
But i want that the random number from two List<> List<int> integers and List<int> value2 . so how can i do this .

You can do something like this:
var result =
integers.Concat(value2)
.OrderBy(x => random.Next())
.Take(count)
.ToList();

You could write a general-purpose function to give you a random ordering of any number of sequences, like so:
public static IReadOnlyCollection<T> InRandomOrder<T>(Random rng, params IEnumerable<T>[] lists)
{
return lists
.SelectMany(x => x)
.OrderBy(y => rng.Next())
.ToList();
}
You can then pass as many lists as you like and get the contents back in a fully randomised order:
var list1 = new[] {1, 2, 3, 4, 5};
var list2 = new[] {6, 7, 8};
var list3 = new[] {9, 0};
Random rng = new Random();
for (int i = 0; i < 10; ++i)
{
var randomisedFirst5 = InRandomOrder(rng, list1, list2, list3).Take(5);
Console.WriteLine(string.Join(", ", randomisedFirst5));
}
There's a less efficient approach you can use that avoids the need for an instance of Random, but you should only use this for short lists or where you really don't care about performance. It uses Guid.NewGuid() to generate random numbers:
public static IReadOnlyCollection<T> InRandomOrder<T>(params IEnumerable<T>[] lists)
{
return lists
.SelectMany(x => x)
.OrderBy(y => Guid.NewGuid())
.ToList();
}
Even the more efficient approach isn't the fastest. A faster way would be to use reservoir sampling to take the first N items that you want, and put them into an array which you shuffle using Knuth. That would make it a lot faster, at the expense of more complicated code - meaning you should only do it the fast way if it's really needed.

If what you want is to select a number that exists either in list A or B, randomly, you can do:
List<int> integers = new List<int>() { 54, 23, 76, 123, 93, 7, 3489 };
List<int> value2 = new List<int>() { 1, 3, 4, 6, 8, 17, 40 };
List<int> allInOne = new List<int>(integers.Concat(value2));
Random r = new Random(DateTime.Now.Millisecond);
/********************************
For demonstration purposes
********************************/
for(int i = 0; i < 5; i++)
{
var randomListIndex = r.Next(0, allInOne.Count - 1);
Console.WriteLine(allInOne[randomListIndex]);
}

Use KeyValuePair
static void Main(string[] args)
{
List<KeyValuePair<int, int>> results = GenerateRandom(100);
}
static List<int> integers = new List<int>() { 54, 23, 76, 123, 93, 7, 3489 };
static List<int> value2 = new List<int>() { 1, 3, 4, 6, 8, 17, 40 };
static Random random = new Random();
public static List<KeyValuePair<int,int>> GenerateRandom(int count)
{
List<KeyValuePair<int,int>> result = new List<KeyValuePair<int,int>>();
for(int i = 0; i < count; i++)
{
int firstValue = integers[random.Next(0, integers.Count - 1)];
int seconValue = value2[random.Next(0, value2.Count - 1)];
result.Add(new KeyValuePair<int,int>(firstValue,seconValue));
}
return result;
}​

I actually made a library a while back that handles some of this stuff : Underscore.cs
It's a nuget package so easy to install, the code to shuffle or take a sample randomly of two lists is :
var ls1 = GenerateRandom(10);
var ls2 = GenerateRandom(20);
var mixer = ls1.Concat(ls2).ToList();
//if you want all of the items shuffled use shuffle
var result = _.List.Shuffle(mixer);
//or if you want a subset randomly sorted use sample
result = _.List.Sample(mixer);

Related

Most efficient way to distribute non unique elements across multiple lists

Suppose that I have a list of integer or whatever
List<int> motherlist = { 1, 1, 2, 5, 7, 2, 2, 2, 6, 1 }
Console.WriteLine(children.Count); // 10
I would like to find all duplicates and not remove them from the list but to distribute them across other lists so the final count of all childrens should be the same as motherlist:
List<List<int>> children = { { 1, 2, 5, 7, 6 }, { 1, 2 }, { 1, 2 }, { 2 }}
Console.WriteLine(children.Sum(l => l.Count())); // 10 same as mother
I tried so far a brute force approach by looping through all elements of mother, comparing the elements with all other elements and to check for duplicates, If duplicate found I add it to a list of buckets (List of Lists) and so forth until the last elements.
But the brute force approach takes 7 CPU seconds for only a mother list of 300 items.
I imagine that if I had 1000 items this would take forever.
Is there a faster way to do this in C# .NET ?
I suggest grouping duplicates and then loop taking into account size of the groups:
public static IEnumerable<List<T>> MyDo<T>(IEnumerable<T> source,
IEqualityComparer<T> comparer = null) {
if (null == source)
throw new ArgumentNullException(nameof(source));
var groups = new Dictionary<T, List<T>>(comparer ?? EqualityComparer<T>.Default);
int maxLength = 0;
foreach (T item in source) {
if (!groups.TryGetValue(item, out var list))
groups.Add(item, list = new List<T>());
list.Add(item);
maxLength = Math.Max(maxLength, list.Count);
}
for (int i = 0; i < maxLength; ++i) {
List<T> result = new List<T>();
foreach (var value in groups.Values)
if (i < value.Count)
result.Add(value[i]);
yield return result;
}
}
Demo:
int[] source = new int[] { 1, 1, 2, 5, 7, 2, 2, 2, 6, 1 };
var result = MyDo(source).ToList();
string report = string.Join(Environment.NewLine, result
.Select(line => $"[{string.Join(", ", line)}]"));
Console.Write(report);
Outcome:
[1, 2, 5, 7, 6]
[1, 2]
[1, 2]
[2]
Stress Demo:
Random random = new Random(1234); // seed, the results to be reproducible
// We don't want 1000 items be forever; let's try 1_000_000 items
int[] source = Enumerable
.Range(1, 1_000_000)
.Select(x => random.Next(1, 1000))
.ToArray();
Stopwatch sw = new Stopwatch();
sw.Start();
var result = MyDo(source).ToList();
sw.Stop();
Console.WriteLine($"Time: {sw.ElapsedMilliseconds} ms");
Outcome: (may vary from workstation to workstation)
Time: 50 ms
I would GroupBy the elements of the list, and then use the count of elements to know the number of sublists an element has to be added in
List<int> motherlist = new List<int> { 1, 1, 2, 5, 7, 2, 2, 2, 6, 1 };
var childrens = motherlist.GroupBy(x => x).OrderByDescending(x => x.Count());
var result = new List<List<int>>();
foreach (var children in childrens)
{
for (var i = 0; i < children.Count(); i++)
{
if (result.Count() <= i) result.Add(new List<int>());
result[i].Add(children.Key);
}
}
Console.WriteLine("{");
foreach (var res in result)
{
Console.WriteLine($"\t{{ { string.Join(", ", res) } }}");
}
Console.WriteLine("}");
This outputs :
{
{ 2, 1, 5, 7, 6 }
{ 2, 1 }
{ 2, 1 }
{ 2 }
}
Just a quick shot, but it seems to work quite well...
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
List<int> motherlist = new List<int> { 1, 1, 2, 5, 7, 2, 2, 2, 6, 1 };
var rnd = new Random(1);
for (int i = 0; i < 1000; i++)
{
motherlist.Add(rnd.Next(1, 200));
}
var resultLists = new List<IEnumerable<int>>();
while (motherlist.Any())
{
var subList = motherlist.Distinct().OrderBy(x => x).ToList();
subList.ForEach(x => motherlist.Remove(x));
resultLists.Add(subList);
}
}
}
}
You can use a Dictionary<int, int> to keep track of the number of occurrences of each element and build the child lists in a single iteration with O(n) time complexity(most of the time) and without any LINQ:
var motherlist = new List<int>() { 1, 1, 2, 5, 7, 2, 2, 2, 6, 1 };
var counts = new Dictionary<int, int>();
var children = new List<List<int>>();
foreach(var element in motherlist)
{
counts.TryGetValue(element, out int count);
counts[element] = ++count;
if (children.Count < count)
{
children.Add(new List<int>() { element });
}
else
{
children[count - 1].Add(element);
}
}
OUTPUT
{ 1, 2, 5, 7, 6 }
{ 1, 2 }
{ 2, 1 }
{ 2 }

Merge multiple lists with variable length "popping" elements from each

I'd like to sort multiple lists (variable number of them) into single list, but keeping the specific order. For example:
List A: { 1,2,3,4,5 }
List B: { 6,7,8 }
List C: { 9,10,11,12 }
Result List: { 1,6,9,2,7,10,3,8,11,4,12,5 }
The only idea I got was to remove the first element from each list and put it into resulting set (and repeat until all lists are empty), but maybe there is a better way that doesn't require to create copy of each list and doesn't affect the original lists as well?
I suggest using IEnumerator<T> to enumerate lists while they have items:
private static IEnumerable<T> Merge<T>(params IEnumerable<T>[] sources) {
List<IEnumerator<T>> enums = sources
.Select(source => source.GetEnumerator())
.ToList();
try {
while (enums.Any()) {
for (int i = 0; i < enums.Count;)
if (enums[i].MoveNext()) {
yield return enums[i].Current;
i += 1;
}
else {
// exhausted, let's remove enumerator
enums[i].Dispose();
enums.RemoveAt(i);
}
}
}
finally {
foreach (var en in enums)
en.Dispose();
}
}
Test
List<int> A = new List<int>() { 1, 2, 3, 4, 5 };
List<int> B = new List<int>() { 6, 7, 8 };
List<int> C = new List<int>() { 9, 10, 11, 12 };
var result = Merge(A, B, C)
.ToList();
Console.Write(string.Join(", ", result));
The outcome is
1, 6, 9, 2, 7, 10, 3, 8, 11, 4, 12, 5
For more flexible use
public static string MergeArrays(params IList<int>[] items)
{
var result = new List<int>();
for (var i = 0; i < items.Max(x => x.Count); i++)
result.AddRange(from rowList in items where rowList.Count > i select rowList[i]);
return string.Join(",", result);
}
.
var a = new List<int>() { 1, 2, 3, 4, 5 };
var b = new List<int>() { 6, 7, 8 };
var c = new List<int>() { 9, 10, 11, 12, 0, 2, 1 };
var r = MergeArrays(a, b, c);
There is no sense in over complicating this in my opinion, why not use a simple for loop to accomplish what you need?
List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };
List<int> list2 = new List<int> { 6, 7, 8 };
List<int> list3 = new List<int> { 9, 10, 11, 12 };
List<int> resultList = new List<int>();
for (int i = 0; i < list1.Count || i < list2.Count || i < list3.Count; i++)
{
if (i < list1.Count) resultList.Add(list1[i]);
if (i < list2.Count) resultList.Add(list2[i]);
if (i < list3.Count) resultList.Add(list3[i]);
}
Result: 1,6,9,2,7,10,3,8,11,4,12,5
Here's a fairly simple way. It was fun to write up anyway.
No, it isn't the best, but it works and you could expand it to suit your needs of using a List<List<int>> very easily.
//Using arrays for simplicity, you get the idea.
int[] A = { 1, 2, 3, 4, 5 };
int[] B = { 6, 7, 8 };
int[] C = { 9, 10, 11, 12 };
List<int> ResultSet = new List<int>();
//Determine this somehow. I'm doing this for simplicity.
int longest = 5;
for (int i = 0; i < longest; i++)
{
if (i < A.Length)
ResultSet.Add(A[i]);
if (i < B.Length)
ResultSet.Add(B[i]);
if (i < C.Length)
ResultSet.Add(C[i]);
}
//ResultSet contains: { 1, 6, 9, 2, 7, 10, 3, 8, 11, 4, 12, 5 }
As you can see, just pop this out into a method and loop through your lists of lists, properly determining the max length of all lists.
I'd go with:
static void Main(string[] args)
{
var a = new List<int>() { 1, 2, 3, 4, 5 };
var b = new List<int>() { 6, 7, 8 };
var c = new List<int>() { 9, 10, 11, 12 };
var abc = XYZ<int>(new[] { a, b, c }).ToList();
}
static IEnumerable<T> XYZ<T>(IEnumerable<IList<T>> lists)
{
if (lists == null)
throw new ArgumentNullException();
var finished = false;
for (int index = 0; !finished; index++)
{
finished = true;
foreach (var list in lists)
if (list.Count > index) // list != null (prior checking for count)
{
finished = false;
yield return list[index];
}
}
}
I had to use use IList to have indexer and Count. It doesn't creates anything (no enumerators, no lists, etc.), purely yield return.
For your problem I create static method, which can merge any collections as you want:
public static class CollectionsHandling
{
/// <summary>
/// Merge collections to one by index
/// </summary>
/// <typeparam name="T">Type of collection elements</typeparam>
/// <param name="collections">Merging Collections</param>
/// <returns>New collection {firsts items, second items...}</returns>
public static IEnumerable<T> Merge<T>(params IEnumerable<T>[] collections)
{
// Max length of sent collections
var maxLength = 0;
// Enumerators of all collections
var enumerators = new List<IEnumerator<T>>();
foreach (var item in collections)
{
maxLength = Math.Max(item.Count(), maxLength);
if(collections.Any())
enumerators.Add(item.GetEnumerator());
}
// Set enumerators to first item
enumerators.ForEach(e => e.MoveNext());
var result = new List<T>();
for (int i = 0; i < maxLength; i++)
{
// Add elements to result collection
enumerators.ForEach(e => result.Add(e.Current));
// Remobve enumerators, in which no longer have elements
enumerators = enumerators.Where(e => e.MoveNext()).ToList();
}
return result;
}
}
Example of using:
static void Main(string[] args)
{
var a = new List<int> { 1, 2, 3, 4, 5 };
var b = new List<int> { 6, 7, 8 };
var c = new List<int> { 9, 10, 11, 12 };
var result= CollectionsHandling.Merge(a, b, c);
}
When you understand how it works, it will be possible to reduce the method of smaller.
Shortest and probably slowest solution
int[] A = { 1, 2, 3, 4, 5 };
int[] B = { 6, 7, 8 };
int[] C = { 9, 10, 11, 12 };
var arrs = new[] { A, B, C };
var merged = Enumerable.Range(0, arrs.Max(a => a.Length))
.Select(x => arrs.Where(a=>a.Length>x).Select(a=>a[x]))
.SelectMany(x=>x)
.ToArray();
upd.
Another way to solve - I just refactored #Sinatr answer.
static IEnumerable<T> XYZ<T>(IEnumerable<IList<T>> lists)
{
if (lists == null)
throw new ArgumentNullException();
var index = 0;
while (lists.Any(l => l.Count > index))
{
foreach (var list in lists)
if (list.Count > index)
yield return list[index];
index++;
}
}

Get common elements with index from two list C#

I have Two lists of type list<int> and i know we can find the common elements between two lists. But is there any way to get common elements and corresponding indexes of common elements in Intersected list or i need to go across each elements find the indexes.
LINQ has operations to project a sequence using indexes, but this isn't built into the query expression syntax, so you have to use "regular" extension method calls to start with. After that it's fairly easy, although probably just as simple not using LINQ, to be honest:
var pairs1 = list1.Select((value, index) => new { value, index });
var pairs2 = list2.Select((value, index) => new { value, index });
var matches = from pair1 in pairs1
join pair2 in pairs2 on pair1.value equals pair2.value
select new
{
Value = pair1.value,
Index1 = pair1.index,
Index2 = pair2.index
};
(You could use from pair2 in pairs2 where pair1.value == pair2.value if you'd prefer...)
Or non-LINQ (using Tuple<,,> for simplicity; other options are feasible):
var results = new List<Tuple<int, int, int>>();
for (int index1 = 0; index1 < list1.Count; index1++)
{
for (int index2 = 0; index2 < list2.Count; index2++)
{
if (list1[index1] == list2[index2])
{
results.Add(Tuple.Of(list1[index1], index1, index2);
}
}
}
Note that unlike a regular intersection operation, both of these can give you multiple results for the same value - because there can be multiple index pairs. For example, with lists of { 1, 2 } and {2, 2, 0}, you'd have tuples of (value=2,index1=1,index2=0), (value=2,index1=1,index2=1).
try below code
List<int> lstA = new List<int>() { 10, 2, 7, 9, 13, 21, 17 };
List<int> lstB = new List<int>() { 2, 10, 7, 21, 13, 9, 17 };
var lstA_Temp = lstA.Select((value, index) => new { index, value }).ToList();
var lstB_Temp = lstB.Select((value, index) => new { index, value }).ToList();
List<int> result = (from A in lstA_Temp from B in lstB_Temp
where A.index == B.index where A.value == B.value
select A.value).ToList();
you can also do this thing without linq see below logic
List<int> lstA = new List<int>() { 10, 2, 7, 9, 13, 21, 17 };
List<int> lstB = new List<int>() { 2, 10, 7, 21, 13, 9, 17 };
List<int> lstResult = new List<int>();
for (int i = 0; i < lstA.Count; i++)
{
if (lstA[i] == lstB[i])
lstResult.Add(lstA[i]);
}

How to find complex permutations based on and/or rules of lists of numbers, C#/Linq

The current problem is that the code works, but it gets exponentially slower as more combinations are passed in. (The calculation takes > 5 seconds after 15 combinations are passed in.) I need to be able to pass in up to 100 combinations and still get a result back that takes less than 2 seconds.
I'm betting that a Linq query could solve this?
What I want to achieve:
{1, 2, 3} + {1, 5, 26, 40} = 12 combinations:
[1,1]
[1,5]
[1,26]
[1,40]
[2,1]
[2,5]
[2,26]
[2,40]
[3,1]
[3,5]
[3,26]
[3,40]
However, this example above only includes 2 combination sets. I should be able to pass in any number of combination sets.
The closest thing that looks like it is similar to what I want as an end result, due to being fast and efficient, is a linq query that handles most or all of the logic within it. Example: Getting all possible combinations from a list of numbers
public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}
Example of working code:
[Test]
public void StackOverflowExample_Simple()
{
var list1 = new List<int>() { 1, 2, 3 };
var list2 = new List<int>() { 1, 5, 26, 40 };
var myListsOfNumberCombinations = new List<List<int>>() { list1, list2 };
var results = GetAllPossibleCombinations(myListsOfNumberCombinations);
Assert.AreEqual(12, results.Count());
StringBuilder sb = new StringBuilder();
foreach (var result in results)
{
foreach (var number in result.OrderBy(x => x))
{
sb.Append(number + ",");
}
sb.Append("|");
}
string finalResult = sb.ToString().Replace(",|", "|");
Assert.AreEqual(finalResult, "1,1|1,5|1,26|1,40|1,2|2,5|2,26|2,40|1,3|3,5|3,26|3,40|");
}
[Test]
public void StackOverflowExample_TakesALongTime()
{
var list1 = new List<int>() { 1, 2, 3 };
var list2 = new List<int>() { 4, 5 };
var list3 = new List<int>() { 1, 6 };
var list4 = new List<int>() { 2, 5 };
var list5 = new List<int>() { 1, 3, 55, 56 };
var list6 = new List<int>() { 3, 4, 7, 8, 9 };
var myListsOfNumberCombinations = new List<List<int>>() { list1, list2, list3, list4, list5, list1, list1, list1, list3, list4, list4, list5, list6, list6, list2 };
DateTime startTime = DateTime.Now;
var results = GetAllPossibleCombinations(myListsOfNumberCombinations);
Assert.AreEqual(4147200, results.Count());
var duration = DateTime.Now.Subtract(startTime).TotalSeconds;
//duration = about 4 or 5 seconds
Assert.Less(duration, 10); //easy place to put a breakpoint
}
public IEnumerable<IEnumerable<int>> GetAllPossibleCombinations(List<List<int>> combinationSets)
{
List<List<int>> returnList = new List<List<int>>();
_RecursiveGetMoreCombinations(
ref returnList,
new List<int>(),
combinationSets,
0);
return returnList;
}
private void _RecursiveGetMoreCombinations(
ref List<List<int>> returnList,
List<int> appendedList,
List<List<int>> combinationSets,
int index)
{
var combinationSet = combinationSets[index];
foreach (var number in combinationSet)
{
List<int> newList = appendedList.AsEnumerable().ToList();
newList.Add(number);
if (combinationSets.Count() == index + 1)
{
returnList.Add(newList);
}
else
{
_RecursiveGetMoreCombinations(
ref returnList,
newList,
combinationSets,
index + 1);
}
}
}
Can you not just do permutations of the first and third sets (the OR sets) and then place '45' (the AND set), or whatever the static numbers are, in between those numbers?
You don't need to include 4 and 5 (in this example) in the permutation logic if they are always going to be present.

Conversion of System.Array to List

Last night I had dream that the following was impossible. But in the same dream, someone from SO told me otherwise. Hence I would like to know if it it possible to convert System.Array to List
Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);
to
List<int> lst = ints.OfType<int>(); // not working
Save yourself some pain...
using System.Linq;
int[] ints = new [] { 10, 20, 10, 34, 113 };
List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.
Can also just...
List<int> lst = new List<int> { 10, 20, 10, 34, 113 };
or...
List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);
or...
List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });
or...
var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
There is also a constructor overload for List that will work... But I guess this would required a strong typed array.
//public List(IEnumerable<T> collection)
var intArray = new[] { 1, 2, 3, 4, 5 };
var list = new List<int>(intArray);
... for Array class
var intArray = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
intArray.SetValue(i, i);
var list = new List<int>((int[])intArray);
Interestingly no one answers the question, OP isn't using a strongly typed int[] but an Array.
You have to cast the Array to what it actually is, an int[], then you can use ToList:
List<int> intList = ((int[])ints).ToList();
Note that Enumerable.ToList calls the list constructor that first checks if the argument can be casted to ICollection<T>(which an array implements), then it will use the more efficient ICollection<T>.CopyTo method instead of enumerating the sequence.
The simplest method is:
int[] ints = new [] { 10, 20, 10, 34, 113 };
List<int> lst = ints.ToList();
or
List<int> lst = new List<int>();
lst.AddRange(ints);
In the case you want to return an array of enums as a list you can do the following.
using System.Linq;
public List<DayOfWeek> DaysOfWeek
{
get
{
return Enum.GetValues(typeof(DayOfWeek))
.OfType<DayOfWeek>()
.ToList();
}
}
in vb.net just do this
mylist.addrange(intsArray)
or
Dim mylist As New List(Of Integer)(intsArray)
You can do like this basically:
int[] ints = new[] { 10, 20, 10, 34, 113 };
this is your array, and than you can call your new list like this:
var newList = new List<int>(ints);
You can do this for complex object too.
You can just give it try to your code:
Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);
int[] anyVariable=(int[])ints;
Then you can just use the anyVariable as your code.
I know two methods:
List<int> myList1 = new List<int>(myArray);
Or,
List<int> myList2 = myArray.ToList();
I'm assuming you know about data types and will change the types as you please.
Just use the existing method.. .ToList();
List<int> listArray = array.ToList();
KISS(KEEP IT SIMPLE SIR)
I hope this is helpful.
enum TESTENUM
{
T1 = 0,
T2 = 1,
T3 = 2,
T4 = 3
}
get string value
string enumValueString = "T1";
List<string> stringValueList = typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
Convert.ToString(m)
).ToList();
if(!stringValueList.Exists(m => m == enumValueString))
{
throw new Exception("cannot find type");
}
TESTENUM testEnumValueConvertString;
Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);
get integer value
int enumValueInt = 1;
List<int> enumValueIntList = typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
Convert.ToInt32(m)
).ToList();
if(!enumValueIntList.Exists(m => m == enumValueInt))
{
throw new Exception("cannot find type");
}
TESTENUM testEnumValueConvertInt;
Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);

Categories

Resources