how to pass multiple objects into a IEnumerable List? - c#

I have this piece of code, which seems to support passing into it many list arguments and it would compare each one against each other one to find a common list among all of the other lists simultaneously.
I cannot figure out how to pass multiple Lists into a single argument thats a IEnmerable.
Say my test code looks like this
List<uint> List1 = new List<uint>();
List<uint> List2 = new List<uint>();
List<uint> List3 = new List<uint>();
List<uint> Commons = FindCommon(List1, List2, List3); //no compile
List<uint> Commons = FindCommon<List<uint>>(List1, List2, List3); //no compile?? why
How do I call this properly?? must I merge them somehow into a IEnumerable?? or must I somehow combine them all into 1 list yet keeping some kind of invisible divider?
static List<T> FindCommon<T>(IEnumerable<List<T>> lists)
{
Dictionary<T, int> map = new Dictionary<T, int>();
int listCount = 0; // number of lists
foreach (IEnumerable<T> list in lists)
{
listCount++;
foreach (T item in list)
{
// Item encountered, increment count
int currCount;
if (!map.TryGetValue(item, out currCount))
currCount = 0;
currCount++;
map[item] = currCount;
}
}
List<T> result= new List<T>();
foreach (KeyValuePair<T,int> kvp in map)
{
// Items whose occurrence count is equal to the number of lists are common to all the lists
if (kvp.Value == listCount)
result.Add(kvp.Key);
}
return result;
}
P.S.> FindCommon is broken somehow it doesn't work properly, probably isn't intended what I thought it should do.. it doesn't check all lists simultaneously together only linear one list at a time with another list which breaks it's purpose, it counts them up.. but it doesn't keep track from which list they came from.
Fixed it like so, this method worked as intended.
public static List<T> FindCommon<T>(params List<T>[] lists)
{
SortedDictionary<T, bool>
current_common = new SortedDictionary<T, bool>(),
common = new SortedDictionary<T, bool>();
foreach (List<T> list in lists)
{
if (current_common.Count == 0)
{
foreach (T item in list)
{
common[item] = true;
}
}
else
{
foreach (T item in list)
{
if (current_common.ContainsKey(item))
{
common[item] = true;
}
}
}
if (common.Count == 0)
{
current_common.Clear();
break;
}
SortedDictionary<T, bool>
swap = current_common;
current_common = common;
common = swap;
common.Clear();
}
return new List<T>(current_common.Keys);
}

You can accomplish this nicely using the params keyword. In your example:
static List<T> FindCommon<T>(params List<T>[] lists)
That would achieve usage:
List<uint> Commons = FindCommon(List1, List2, List3);

You need to Add list1,list2,list3 in another list like ,
List<List<uint>> commonLists=new List<List<uint>>();
commonLists.Add(list1);
commonLists.Add(list2);
commonLists.Add(list3);
List<uint> commons=FindCommon<List<unit>>(commonLists);

Related

algorithm for selecting N random elements from a List<T> in C# [duplicate]

This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 6 years ago.
I need a quick algorithm to select 4 random elements from a generic list. For example, I'd like to get 4 random elements from a List and then based on some calculations if elements found not valid then it should again select next 4 random elements from the list.
You could do it like this
public static class Extensions
{
public static Dictionary<int, T> GetRandomElements<T>(this IList<T> list, int quantity)
{
var result = new Dictionary<int, T>();
if (list == null)
return result;
Random rnd = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < quantity; i++)
{
int idx = rnd.Next(0, list.Count);
result.Add(idx, list[idx]);
}
return result;
}
}
Then use the extension method like this:
List<string> list = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h" };
Dictionary<int, string> randomElements = list.GetRandomElements(3);
foreach (KeyValuePair<int, string> elem in randomElements)
{
Console.WriteLine($"index in original list: {elem.Key} value: {elem.Value}");
}
something like that:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int n = 4;
var rand = new Random();
var randomObjects = new List<int>();
for (int i = 0; i<n; i++)
{
var index = rand.Next(list.Count);
randomObjects.Add(list[index]);
}
}
}
You can store indexes in some list to get non-repeated indexes:
List<T> GetRandomElements<T>(List<T> allElements, int randomCount = 4)
{
if (allElements.Count < randomCount)
{
return allElements;
}
List<int> indexes = new List<int>();
// use HashSet if performance is very critical and you need a lot of indexes
//HashSet<int> indexes = new HashSet<int>();
List<T> elements = new List<T>();
Random random = new Random();
while (indexes.Count < randomCount)
{
int index = random.Next(allElements.Count);
if (!indexes.Contains(index))
{
indexes.Add(index);
elements.Add(allElements[index]);
}
}
return elements;
}
Then you can do some calculation and call this method:
void Main(String[] args)
{
do
{
List<int> elements = GetRandomelements(yourElements);
//do some calculations
} while (some condition); // while result is not right
}
Suppose that the length of the List is N. Now suppose that you will put these 4 numbers in another List called out. Then you can loop through the List and the probability of the element you are on being chosen is
(4 - (out.Count)) / (N - currentIndex)
funcion (list)
(
loop i=0 i < 4
index = (int) length(list)*random(0 -> 1)
element[i] = list[index]
return element
)
while(check == false)
(
elements = funcion (list)
Do some calculation which returns check == false /true
)
This is the pseudo code, but i think you should of come up with this yourself.
Hope it helps:)
All the answers up to now have one fundamental flaw; you are asking for an algorithm that will generate a random combination of n elements and this combination, following some logic rules, will be valid or not. If its not, a new combination should be produced. Obviously, this new combination should be one that has never been produced before. All the proposed algorithms do not enforce this. If for example out of 1000000 possible combinations, only one is valid, you might waste a whole lot of resources until that particular unique combination is produced.
So, how to solve this? Well, the answer is simple, create all possible unique solutions, and then simply produce them in a random order. Caveat: I will suppose that the input stream has no repeating elements, if it does, then some combinations will not be unique.
First of all, lets write ourselves a handy immutable stack:
class ImmutableStack<T> : IEnumerable<T>
{
public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
private readonly T head;
private readonly ImmutableStack<T> tail;
public int Count { get; }
private ImmutableStack()
{
Count = 0;
}
private ImmutableStack(T head, ImmutableStack<T> tail)
{
this.head = head;
this.tail = tail;
Count = tail.Count + 1;
}
public T Peek()
{
if (this == Empty)
throw new InvalidOperationException("Can not peek a empty stack.");
return head;
}
public ImmutableStack<T> Pop()
{
if (this == Empty)
throw new InvalidOperationException("Can not pop a empty stack.");
return tail;
}
public ImmutableStack<T> Push(T item) => new ImmutableStack<T>(item, this);
public IEnumerator<T> GetEnumerator()
{
var current = this;
while (current != Empty)
{
yield return current.head;
current = current.tail;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
This will make our life easier while producing all combinations by recursion. Next, let's get the signature of our main method right:
public static IEnumerable<IEnumerable<T>> GetAllPossibleCombinationsInRandomOrder<T>(
IEnumerable<T> data, int combinationLength)
Ok, that looks about right. Now let's implement this thing:
var allCombinations = GetAllPossibleCombinations(data, combinationLength).ToArray();
var rnd = new Random();
var producedIndexes = new HashSet<int>();
while (producedIndexes.Count < allCombinations.Length)
{
while (true)
{
var index = rnd.Next(allCombinations.Length);
if (!producedIndexes.Contains(index))
{
producedIndexes.Add(index);
yield return allCombinations[index];
break;
}
}
}
Ok, all we are doing here is producing random indexees, checking we haven't produced it yet (we use a HashSet<int> for this), and returning the combination at that index.
Simple, now we only need to take care of GetAllPossibleCombinations(data, combinationLength).
Thats easy, we'll use recursion. Our bail out condition is when our current combination is the specified length. Another caveat: I'm omitting argument validation throughout the whole code, things like checking for null or if the specified length is not bigger than the input length, etc. should be taken care of.
Just for the fun, I'll be using some minor C#7 syntax here: nested functions.
public static IEnumerable<IEnumerable<T>> GetAllPossibleCombinations<T>(
IEnumerable<T> stream, int length)
{
return getAllCombinations(stream, ImmutableStack<T>.Empty);
IEnumerable<IEnumerable<T>> getAllCombinations<T>(IEnumerable<T> currentData, ImmutableStack<T> combination)
{
if (combination.Count == length)
yield return combination;
foreach (var d in currentData)
{
var newCombination = combination.Push(d);
foreach (var c in getAllCombinations(currentData.Except(new[] { d }), newCombination))
{
yield return c;
}
}
}
}
And there we go, now we can use this:
var data = "abc";
var random = GetAllPossibleCombinationsInRandomOrder(data, 2);
foreach (var r in random)
{
Console.WriteLine(string.Join("", r));
}
And sure enough, the output is:
bc
cb
ab
ac
ba
ca

C# - finding the common elements in a list of list of integers

I have a list of list of items like in the following.
List<List<int>> testItems=new List<List<int>>();
I have added items to it like this.
List<int> item=new List<item>();
item.clear();
item.Add(3);
item.Add(5);
item.Add(7);
testItems.Add(item);
item.clear();
item.Add(10);
item.Add(3);
testItems.Add(item);
item.clear();
item.Add(1);
item.Add(8);
item.Add(3);
item.Add(9);
testItems.Add(item);
Now what I want to do is I want to extract the elements common to all the lists and add it to another list called finalList.
List<int> finalList = new List<int>();
I have tried the following.
int count;
foreach (List<int> a in testItems)
{
count = 0;
foreach (int b in a)
{
foreach (List<int> c in testItems)
{
foreach (int d in c)
{
if (d == b)
{
count++;
break;
}
}
}
if (count == a.Count)
finalList.Add(b);
}
}
I know this solution is not optimal and does not provide what I need. It can possibly add the same item several times. Can someone help me to fix it ?
Your code for adding items is not adding three different items. As you are reusing the item, the code is equivalent to:
List<int> item=new List<int>();
item.Add(1);
item.Add(8);
item.Add(3);
item.Add(9);
testItems.Add(item);
testItems.Add(item);
testItems.Add(item);
You need to create new items instead of reusing the same item:
List<int> item = new List<int>();
item.Add(3);
item.Add(5);
item.Add(7);
testItems.Add(item);
item = new List<int>();
item.Add(10);
item.Add(3);
testItems.Add(item);
item = new List<int>();
item.Add(1);
item.Add(8);
item.Add(3);
item.Add(9);
testItems.Add(item);
For a more efficient way to get the numbers common to all items, you can loop through all values in the first item, and check which exists in all the other items:
List<int> finalList =
testItems[0].Where(
i => testItems.Skip(1).All(x => x.Contains(i))
).ToList();
You can use LINQ method Intersect
You will get something like this:
IEnumerable<int> result = testItems[0];
for(int i = 1; i < testItems.Count; i++)
{
result = result.Intersect(testItems[i]);
}
You get your intersection in the result variable.
But are you really sure that you need this strange looking list of lists?

compare List<string> and List<T>

I'm using C# and framework 4.0.
I have a list of type string and another list of type class T;
How can I compare List with a List and save the difference?
private void simpleButton_Compare_Click(object sender, EventArgs e)
{
try
{
bool Is_Egal = true;
int i = 0;
foreach (string Od_Scan in Ordre_Scan)
{
if (!Outils.Get_Ordre_Donne()[i].NoOrdre.Contains(Od_Scan) && !String.IsNullOrWhiteSpace(Od_Scan))
{
Is_Egal = false;
Temp_Od_Scan.Add(Od_Scan);
}
i++;
}
foreach (Pers_Compare Od_Done in Outils.Get_Ordre_Donne())
{
if (!Ordre_Scan.Contains(Od_Done.NoOrdre) && !String.IsNullOrWhiteSpace(Od_Done.NoOrdre))
{
Is_Egal = false;
Temp_Od_Donne.Add(Od_Done);
}
else
{
Temp_Od_Donne_Egal.Add(Od_Done);
}
}
if (Is_Egal)
{
MessageBox.Show("égalité");
}
else
{
MessageBox.Show("PAS égalité");
}
}
catch (Exception excThrown)
{
MessageBox.Show(excThrown.Message);
}
}
and the data :
List<string> Ordre_Scan= new List<string> { "azer","qsdf"};
Pers_Compare obj = new Pers_Compare();
obj.Nolv = 1;
obj.Noordre = "qsdf"
Pers_Compare obj2 = new Pers_Compare();
obj2.Nolv = 1;
obj2.Noordre = "wxcv"
List<Pers_Compare> Ordre_Donne = new List<Pers_Compare>();
Ordre_Donne.add(obj);
Ordre_Donne.add(obj2);
And I want to save the data in Ordre_Donne but not in Od_Scan and vice versa.
foreach (string Od_Scan in Temp_Od_Scan)
{
all item that not found in List A
--> wxcv
}
foreach (var Od_Done in Temp_Od_Donne)
{
all item that not found in List B
--> azer
}
The answer given for a slightly different question (comparing a List with another List) seems to me to be a good solution for your issue, they address multiple issues to do with comparisons of lists.
EDIT: However you should be more specific with your requirements i.e. what exactly is a 'difference', e.g. is {1,1,2} and {1,2} the same?
Here is the answer given the most votes... (included here just encase it gets removed for some reason (as per Bob' suggestion))
"
DESCRIPTION:
I need to check that they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list. Is there a built-in function that checks this? What if I guarantee that each element appears only once in a list?
EDIT: Guys thanks for the answers but I forgot to add something, the number of occurrences of each element should be the same on both lists.
ANSWER:
If you want them to be really equal (i.e. the same items and the same number of each item), I think that the simplest solution is to sort before comparing:
Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))
Edit:
Here is a solution that performs a bit better (about ten times faster), and only requires IEquatable, not IComparable:
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
var cnt = new Dictionary<T, int>();
foreach (T s in list1) {
if (cnt.ContainsKey(s)) {
cnt[s]++;
} else {
cnt.Add(s, 1);
}
}
foreach (T s in list2) {
if (cnt.ContainsKey(s)) {
cnt[s]--;
} else {
return false;
}
}
return cnt.Values.All(c => c == 0);
}
Edit 2:
To handle any data type as key (for example nullable types as Frank Tzanabetis pointed out), you can make a version that takes a comparer for the dictionary:
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
var cnt = new Dictionary<T, int>(comparer);
...
"
var list1 = Ordre_Donne.Where(o => !Ordre_Scan.Any(s => s == o.Noordre));
var list2 = Ordre_Scan.Where(s => !Ordre_Donne.Any(o => o.Noordre == s));
You can either implement IComparable on your Pers_Compare class, which will look something like:
public int CompareTo(string other)
{
return this.Noordre.CompareTo(other);
}
Or, if you don't have control of the data structure, you could do something like
var Temp_Od_Donne = from od in Ordre_Donne
where !Ordre_Scan.Contains(od.Noordre)
select od;
var Temp_Od_Scan = from os in Ordre_Scan
where !Ordre_Donne.Select(od => od.Noordre).Contains(os)
select os;

Merge and Update Two Lists in C#

I have two List<T> objects:
For example:
List 1:
ID, Value where Id is populated and value is blank and it contains say IDs from 1 to 10.
1,""
2,""
...
10,""
List 2:
ID, Value and other attributes all filled with values but this list is a subset of List 1 in terms of IDs. (e.g only 3 items)
2,67
4,90
5,98
What I want is a merged list 1, but with updated values. Does anyone have any good extension method which will do this or any elegent code to perform this operation. The final list should be:
ID, Value
1,""
2,67 //value from list 2
3,""
4,90
5,98
6,""
...
10,""
use linq: list1=list2.Union(list1);
I would probably use a dictionary rather than a list:
// sample data
var original = new Dictionary<int, int?>();
for (int i = 1; i <= 10; i++)
{
original.Add(i, null);
}
var updated = new Dictionary<int, int>();
updated.Add(2, 67);
updated.Add(4, 90);
updated.Add(5, 98);
updated.Add(11, 20); // add
// merge
foreach (var pair in updated)
{
original[pair.Key] = pair.Value;
}
// show results
foreach (var pair in original.OrderBy(x => x.Key))
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
If you are talking about properties of an object, it will be trickier, but still doable.
This is O(m*n) but should do the job for arbitrary lists
foreach (var record in List1)
{
var other = List2.FirstOrDefault(x => x.Key == record.Key);
if(other != null) record.Value = other.Value;
}
If the lists are guaranteed ordered, then it could be brought down to O(n) at the cost of more code. The algortihm would be
Current items start as head of each list
While items remain in both lists
If the current item of list1 has lower key than list2 advance to next in list1
else if the current item of list2 has lower key than list1 advance to next in list2
else copy value from current list2 item into list1 item and advance both lists.
If you have both lists sorted by ID, you can use a variation of the classical merge algorithm:
int pos = 0;
foreach (var e in list2) {
pos = list1.FindIndex(pos, x => x.Id==e.Id);
list1[pos].Value = e.Value;
}
Note that this also requires list2 to be a strict subset of list1 in terms of ID (i.e. list1 really contains all ids of list2)
Of course you can also wrap this in an extension method
public static void UpdateWith<T>(this List<T> list1, List<T> list2)
where T:SomeIdValueSupertype {
int pos = 0;
foreach (var e in list2) {
pos = list1.FindIndex(pos, x => x.Id==e.Id);
list1[pos].Value = e.Value;
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
String searchBy = cmbSearchBy.Text.ToString();
String searchFor = txtSearchFor.Text.Trim();
var List3 = (from row in JobTitleDB.jobList
where (row.JID.ToString()+row.JobTitleName.ToString().ToLower()).Contains(searchFor.ToLower())
select row).ToList();
if (searchBy == "All")
{
dgJobTitles.DataSource = null;
//dgJobTitles.DataSource = List1;
//dgJobTitles.DataSource = List2;
//dgJobTitles.DataSource = List1.Concat(List2);
//dgJobTitles.DataSource = List1.Union(List2);
dgJobTitles.DataSource = List3;
//dgJobTitles.DataSource=List1.AddRange(List2);
}
}
Dictionary<int, string> List1 = new Dictionary<int, string>();
List1.Add(1,"");
List1.Add(2,"");
List1.Add(3,"");
List1.Add(4,"");
List1.Add(5,"");
List1.Add(6,"");
Dictionary<int, string> List2 = new Dictionary<int, string>();
List2.Add(2, "two");
List2.Add(4, "four");
List2.Add(6, "six");
var Result = List1.Select(x => new KeyValuePair<int, string>(x.Key, List2.ContainsKey(x.Key) ? List2[x.Key] : x.Value)).ToList();

Multi-dimensional arraylist or list in C#?

Is it possible to create a multidimensional list in C#?
I can create an multidimensional array like so:
string[,] results = new string[20, 2];
But I would like to be able to use some of the features in a list or arraylist like being able to add and delete elements.
You can create a list of lists
public class MultiDimList: List<List<string>> { }
or a Dictionary of key-accessible Lists
public class MultiDimDictList: Dictionary<string, List<int>> { }
MultiDimDictList myDicList = new MultiDimDictList ();
myDicList.Add("ages", new List<int>());
myDicList.Add("Salaries", new List<int>());
myDicList.Add("AccountIds", new List<int>());
Generic versions, to implement suggestion in comment from #user420667
public class MultiDimList<T>: List<List<T>> { }
and for the dictionary,
public class MultiDimDictList<K, T>: Dictionary<K, List<T>> { }
// to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", new List<T>());
myDicList["ages"].Add(23);
myDicList["ages"].Add(32);
myDicList["ages"].Add(18);
myDicList.Add("salaries", new List<T>());
myDicList["salaries"].Add(80000);
myDicList["salaries"].Add(100000);
myDicList.Add("accountIds", new List<T>());
myDicList["accountIds"].Add(321123);
myDicList["accountIds"].Add(342653);
or, even better, ...
public class MultiDimDictList<K, T>: Dictionary<K, List<T>>
{
public void Add(K key, T addObject)
{
if(!ContainsKey(key)) Add(key, new List<T>());
if (!base[key].Contains(addObject)) base[key].Add(addObject);
}
}
// and to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", 23);
myDicList.Add("ages", 32);
myDicList.Add("ages", 18);
myDicList.Add("salaries", 80000);
myDicList.Add("salaries", 110000);
myDicList.Add("accountIds", 321123);
myDicList.Add("accountIds", 342653);
EDIT: to include an Add() method for nested instance:
public class NestedMultiDimDictList<K, K2, T>:
MultiDimDictList<K, MultiDimDictList<K2, T>>:
{
public void Add(K key, K2 key2, T addObject)
{
if(!ContainsKey(key)) Add(key,
new MultiDimDictList<K2, T>());
if (!base[key].Contains(key2))
base[key].Add(key2, addObject);
}
}
you just make a list of lists like so:
List<List<string>> results = new List<List<string>>();
and then it's just a matter of using the functionality you want
results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list
Not exactly. But you can create a list of lists:
var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
var l = new List<int>();
ll.Add(l);
}
Depending on your exact requirements, you may do best with a jagged array of sorts with:
List<string>[] results = new { new List<string>(), new List<string>() };
Or you may do well with a list of lists or some other such construct.
If you want to modify this I'd go with either of the following:
List<string[]> results;
-- or --
List<List<string>> results;
depending on your needs...

Categories