I have two lists of strings. How do I get the list of distinct values between them or remove the second list elements from the first list?
List<string> list1 = { "see","you","live"}
List<string> list2 = { "see"}
The result should be {"you","live"}.
It looks to me like you need Enumerable.Except():
var differences = list1.Except(list2);
And then you can loop through the differences:
foreach(var difference in differences)
{
// work with each individual string here.
}
If you want to get items from the first list except items in the second list, use
list1.Except(list2)
If you want to get items that are in the first list or in the second list, but not both, you can use
list1.Except(list2).Concat(list2.Except(list1))
This is the good way I find unique....
Unique from two list
var A = new List<int>() { 1,2,3,4 };
var B = new List<int>() { 1, 5, 6, 7 };
var a= A.Except(B).ToList();
// outputs List<int>(2) { 2,3,4 }
var b= B.Except(A).ToList();
// outputs List<int>(2) { 5,6,7 }
var abint= B.Intersect(A).ToList();
// outputs List<int>(2) { 1 }
here is my answer,
find distinct value's in two int list and assign that vlaues to the third int list.
List<int> list1 = new List <int>() { 1, 2, 3, 4, 5, 6 };
List<int> list2 = new List<int>() { 1, 2, 3, 7, 8, 9 };
List<int> list3 = new List<int>();
var DifferentList1 = list1.Except(list2).Concat(list2.Except(list1));
foreach (var item in DifferentList1)
{
list3.Add(item);
}
foreach (var item in list3)
{
Console.WriteLine("Different Item found in lists are{0}",item);
}
Console.ReadLine();
Related
Is there a way to make multiple data field merge together and become a single List. There is two array which is
int[] QueueNo = {10, 20, 30, 40};
int [] WaitingTime = {1, 2, 3, 4}
How do I insert this two data into one List
So that I can a foreach loop to insert the data into the database
foreach(var item in list)
{
////Code For Create Data
}
You can zip both lists together:
var result = QueueNo.Zip(WaitingTime, (first, second) => new { first, second });
Now you can foreach this list:
foreach(var e in result)
{
var queueNo = e.first;
var waitingTime = e.second;
}
Alternativly use a normal for-loop on one of the arrays and use the common index:
for(int i = 0; i < QueueNo.Length; i++)
{
var queNo = QueueNo[i];
var waitingTime = WaitingTime[i];
}
You can easily do it. Just use Union
int[] QueueNo = {10, 20, 30, 40};
int [] WaitingTime = {1, 2, 3, 4}
var myList = QueueNo.Union(WaitingTime).ToList();
I have two lists of strings and want to compare them and extract values in such a way that the below scenario holds true :
list1 = {0,1,2,3,3}
list2 = {0,1,2,3}
Expected O/P : 3 .(I need to ignore the values that have a pair in other list and get only the remaining ones).
The item order will remain same in most of scenarios, it would be good if we cover the edge case scenario as well in which the order differs.
Try the below, I think does what you want
List<int> l1 = new List<int>{1, 2, 3, 3};
List<int> l2 = new List<int>{1, 2, 3, 4};
List<int> result = new List<int>();
List<int> l1c = new List<int>();
List<int> l2c = new List<int>();
l1c.AddRange(l1);
l2c.AddRange(l2);
foreach(int item in l1)
l2c.Remove(item);
foreach(int item in l2)
l1c.Remove(item);
result.AddRange(l1c);
result.AddRange(l2c);
Console.WriteLine(string.Join(", ", result));
// this outputs 3, 4
return result;
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.
This question already has answers here:
Combination of List<List<int>>
(9 answers)
Closed 9 years ago.
Differs from sugested solution above in that a list item can only appear once for each row.
This is for a booking system for my spa. Different employees can perform different treatments.
I have a List<List<int>>. These are therapists that can perform the treatment that is booked.
Each list (booking) contain a number of integers like this (these are therapists that can perform the booking):
{1, 3, 6}, //Booking 1
{1, 2, 6}, //Booking 2
{1}, //Booking 3
{2,3} //Booking 4
I'd like to see all possible combinations where the number can only appear in one Place. For the above list the two possible ombinations would be:
6,2,1,3 or
3,6,1,2
That is for the first combination:
Booking 1: Therapist 6
Booking 2: Therapist 2
Booking 3: Therapist 1
Booking 4: Therapist 3
Hope this makes the question a Little bit clearer.
Solve by recursion:
static IEnumerable<List<int>> GetCombinations(IEnumerable<List<int>> lists, IEnumerable<int> selected)
{
if (lists.Any())
{
var remainingLists = lists.Skip(1);
foreach (var item in lists.First().Where(x => !selected.Contains(x)))
foreach (var combo in GetCombinations(remainingLists, selected.Concat(new int[] { item })))
yield return combo;
}
else
{
yield return selected.ToList();
}
}
static void Main(string[] args)
{
List<List<int>> lists = new List<List<int>>
{
new List<int> { 1, 3, 6 },
new List<int> { 1, 2, 6 },
new List<int> { 1 },
new List<int> { 2, 3 }
};
var combos = GetCombinations(lists, new List<int>()).Distinct();
foreach (var combo in combos)
Console.WriteLine("{ " + string.Join(", ", combo.Select(x => x.ToString())) + " }");
return;
}
Output:
{ 3, 6, 1, 2 }
{ 6, 2, 1, 3 }
This solution is far from efficient:
private static void Main()
{
List<List<int>> list = new List<List<int>>
{
new List<int>() {1, 3, 6}, //Booking 1
new List<int>() {1, 2, 6}, //Booking 2
new List<int>() {1}, //Booking 3
new List<int>() {2, 3}
};
List<int[]> solutions = new List<int[]>();
int[] solution = new int[list.Count];
Solve(list, solutions, solution);
}
private static void Solve(List<List<int>> list, List<int[]> solutions, int[] solution)
{
if (solution.All(i => i != 0) && !solutions.Any(s => s.SequenceEqual(solution)))
solutions.Add(solution);
for (int i = 0; i < list.Count; i++)
{
if (solution[i] != 0)
continue; // a caller up the hierarchy set this index to be a number
for (int j = 0; j < list[i].Count; j++)
{
if (solution.Contains(list[i][j]))
continue;
var solutionCopy = solution.ToArray();
solutionCopy[i] = list[i][j];
Solve(list, solutions, solutionCopy);
}
}
}
It sounds like this can be solved more efficiently with Dynamic programming, but it's been a while since I took the relevant course.
A simple way to look at this problem would be to choose from all combinations of the list of values, where every value in the combination is unique.
First figure out what all the combinations of values are.
public static IEnumerable<IList<T>> Combinations<T>(IEnumerable<IList<T>> collections)
{
if (collections.Count() == 1)
{
foreach (var item in collections.Single())
yield return new List<T> { item };
}
else if (collections.Count() > 1)
{
foreach (var item in collections.First())
foreach (var tail in Combinations(collections.Skip(1)))
yield return new[] { item }.Concat(tail).ToList();
}
}
Then you need a way to determine if all the values are unique. A simple way to figure that out would be to check if the count of distinct values equals the count of all values.
public static bool AllUnique<T>(IEnumerable<T> collection)
{
return collection.Distinct().Count() == collection.Count();
}
Once you have all that, put it all together.
var collections = new[]
{
new List<int> { 1, 3, 6 },
new List<int> { 1, 2, 6 },
new List<int> { 1 },
new List<int> { 2, 3 },
};
var results =
from combination in Combinations(collections)
where AllUnique(combination)
select combination;
// results:
// 3,6,1,2
// 6,2,1,3
How find if any list in list of list contains all elements in another list?
Something like list list .contains(list), where list(list) is stanjaDKA, and list is tmpzaNormalanPrijelaz, and all list members are of type int?
I tried this but I get to much states in stanjaDKA at the end.
int indeks=stanjaDKA.FindIndex(x=>x.Equals(tmpzaNormalanPrijelaz));
if (indeks==-1 && tmpzaNormalanPrijelaz.Count>0)
{
stanjaDKA.Add(tmpzaNormalanPrijelaz);
}
How find if any X in list of X
Use LINQ's Any:
bool anyXInListOfX = myListOfX(x => someConditionOnX);
list contains all elements in another list
If you're not concerned about duplicate elements (i.e. if you're happy that {1} contains all the elements in {1, 1}), you can use LINQ's Except and check there is nothing left:
bool firstListContainsAllElementsInSecondList =
!mySecondList.Except(myFirstList).Any();
However, "any list contains all elements" is equivalent to "all lists don't contain all elements", and the don't cancels with the ! in the above, so in your case I'd do something like
if (stanjaDKA.All(l => tmpzaNormalanPrijelaz.Except(l).Any()))
{
stanjaDKA.Add(tmpzaNormalanPrijelaz);
}
This reads as "if all the lists in stanjaDKA are each missing at least one element in tmpzaNormalanPrijelaz, add tmpzaNormalanPrijelaz to stanjaDKA".
depending on what you are really want this will help you to do the mayor stuff
// Sample List<List<int>>
var listList = new List<List<int>>();
listList.Add(new List<int>() { 0, 1, 2, 3, 4 });
listList.Add(new List<int>() { 0, 1, 2, 3, 4 });
listList.Add(new List<int>() { 1, 1, 2, 3, 4 });
listList.Add(new List<int>() { 1, 1, 1, 1, 1 });
listList.Add(new List<int>() { 5, 6, 7, 8, 9 });
// the List you are seaching for
var searchList = new List<int>() { 10 };
foreach(List<int> list in listList)
{
var newList =list.Intersect(searchList);
if (newList.Count() == searchList.Count)
{
string elements = "";
foreach (int item in newList)
{
elements += item + " ";
}
Console.WriteLine(elements);
}
}
Console.ReadLine();
you should also take a look at this Link maybe you need it