This question already has answers here:
Compare two List<T> objects for equality, ignoring order [duplicate]
(9 answers)
Closed 9 years ago.
I want to compare the values of two lists for a program I'm making. I want it to compare the 1st value of List 1 to the first value of List 2, and then the second value of List 1 to the second value of List 2, and so on.
How would I go about doing this in C#?
There is a special method for this, called SequenceEqual:
IList<int> myList1 = new List<int>(...);
IList<int> myList2 = new List<int>(...);
if (myList1.SequenceEqual(list2)) {
...
}
You can do custom comparison of sequences using the Zip method. For example, to see if any pair is not within the difference of three, you can do this:
IList<int> myList1 = new List<int>(...);
IList<int> myList2 = new List<int>(...);
if (myList1.Zip(list2, (a, b) => Math.Abs(a - b)).Any(diff => diff > 3)) {
...
}
Related
This question already has answers here:
Convert a list to a string in C#
(14 answers)
Closed 9 months ago.
I am a mere beginner and I am trying to learn a bit of LINQ. I have a list of values and I want to receive a different list based on some computation. For example, the below is often quoted in various examples across the Internet:
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
here the "computation" is done by simply multiplying a member of the original list by itself.
I wanted to actually use a method that returns a string and takes x as an argument.
Here is the code I wrote:
namespace mytests{
class program {
static void Main (string[] args)
{
List<string> nums = new List<string>();
nums.Add("999");
nums.Add("888");
nums.Add("777");
IEnumerable<string> strings = nums.AsEnumerable().Select(num => GetStrings(num));
Console.WriteLine(strings.ToString());
}
private static string GetStrings (string num){
if (num == "999")
return "US";
else if (num == "888")
{
return "GB";
}
else
{
return "PL";
}
}
}
}
It compiles but when debugging, the method GetStrings is never accessed and the strings object does not have any members. I was expecting it to return "US", "GB", "PL".
Any advice on what I could be doing wrong?
Thanks.
IEnumerable<string>.ToString() method does not work as you expected. Result will be
System.Collections.Generic.List`1[System.String]
If you want to see the values which are held in the collection, you should create iteration.
foreach (var i in strings)
Console.WriteLine(i);
This line does two things for you. One of them is writing the values which are held in the collection to console. The other operation is iterating the collection. During iteration, values are needed and linq will execute the necessary operation (in your case GetStrings method).
Currently your code does not use the collection values, so the code does not evaluate the values and does not trigger GetStrings method.
This question already has answers here:
Best way to combine two or more byte arrays in C#
(13 answers)
Closed 1 year ago.
I have the following list of arrays
var list = new List<string[]>();
how to use LINQ to convert/Join them into a single array
string[] singleArray;
It can be done by SelectMany operator.
var singleArray = list.SelectMany(x => x).ToArray()
This question already has answers here:
Does .NET have a way to check if List a contains all items in List b?
(5 answers)
Closed 7 years ago.
I have 2 int arrays, arr1, and arr2 eg, what is the most efficient way to verify that the arr1 contains All items that arr2 contains. Preferentially returning bool.
eg.
arr1 = [1,2,3,4]
arr2 = [1,2,3,4,5,6,9]
//return true;
arr1 = [1,2,3,4,10]
arr2 = [1,2,3,4,5,6,9]
//return false;
I did It with foreach but I want anything besides brute-force foreach, if is possible.
What about something like:
bool subset = !arr1.Except(arr2).Any();
Would probably be smoothly implemented as an extension method like this:
public static bool ContainsAll<T>(this List<T> list, List<T> other)
{
return !other.Except(list).Any();
}
Usage would then be:
bool subset = arr2.ContainsAll(arr1);
This question already has answers here:
Generating all Possible Combinations
(12 answers)
Closed 7 years ago.
Lets say I have three list:
A = {"b", "c", "d", "x", "y", "z"}
B = {"a", "e", "i"}
I want to generate all combinations of selecting one element from both list.
For just 2 list this is easy (pseuodo-ish code):
combinations = []
for a in A:
for b in B:
combinations += [a, b]
But what if the number of lists is unknown? I want to generalize this somehow preferrably with a C# extension method.
The method signature would be something like this:
public static IEnumerable<IEnumerable<T>> Combination<T>(this IEnumerable<IEnumerable<T>> elements)
EDIT:
I was looking for Cartesian product, thanks for clarification.
If you are just flat combining, and you have a set of these sets, you should be able to simply use a SelectMany on the sets.
public static IEnumerable<[T]> Combination<T>(this IEnumerable<IEnumerable<T>> elements)
{
return elements.Select(
e => elements.Except(e).SelectMany( t => new T[e,t] )
);
}
Assuming you want all combinations including the ones with duplicate elements in a different order, this is basically what the existing method SelectMany does.
It's fairly easy to get all combinations using query expressions and anonymous objects. Here's an example:
var combinations = from a in allAs
from b in allBs
select new { A = a, B = b };
Doing this in one fell swoop (using the proposed Combination method) would at least require you to:
Provide a function to "select" a combination (similar to the signature of the Zip method)
Or, return a generic Tuple<T, T>
But then again, it's really just replacing the usage of a cartesian product (SelectMany) and a projection (Select), both of which already exist.
This question already has answers here:
Converting a List<String> to List<int>
(2 answers)
Closed 9 years ago.
The list is below: I simply want to convert it to an integer list
List<string> list2 = new List<string>();
How do I convert all of it's contents to int?
var intList = list2.Select(x => int.Parse(x)).ToList();
You can use List.ConvertAll<int>:
List<int> ints = list2.ConvertAll<int>(int.Parse);
If you don't have a list you could use a Select with int.Parse:
List<int> ints = strings.Select(s=> int.Parse(s)).ToList();