Linq is a fancy cover for for loops, foreach loops and conditional statements, as result I would construct the above question in terms of for loops and conditionals etc, then afterwards look to convert this into a Linq statement.
e.g
private List<Tuple<double, double>> GetElementsWhosSumIsGreaterThanX(List<double> originalList, double x)
{
//take the absolute value of the variable to eliminate sign errors
x= Math.Abs(x);
List<Tuple<double, double>> returnList = new List<Tuple<double, double>>();
//only go upto count - 1 as there is no more elements to compare the last element to
for (int i = 0; i < originalList.Count - 1; i++)
{//loop over each element in turn
for (int j = i; j < originalList.Count - i; j++)
{//compare it to the rest of the list from the ith element on
double sum = originalList[i] + originalList[j];
if (sum> x)
returnList.Add( new Tuple<double, double>(originalList[i], originalList[j]));
}
}
return returnList;
}
This can be used like:
public void Test()
{
List<double> tags = new List<double>() {5, 7, 9, 13, 10.1, 25.6, 32.1};
List<Tuple<double, double>> results = GetElementsWhosSumIsGreaterThanX(tags, 20);
for (int i = 0; i < results.Count; i++)
{
Console.WriteLine("{0} and {1} have a sum greater than 20", results[i].Item1, results[i].Item2);
}
/*output:
5 and 25.6 have a sum greater than 20
5 and 32.1 have a sum greater than 20
7 and 25.6 have a sum greater than 20
9 and 13 have a sum greater than 20
13 and 13 have a sum greater than 20
*/
}
tags? Can you show the data-structure and some sample-data as well as expected behaviour?tags.SelectMany(t1 => tags.Where(t2 => t2 != t1).Select(t2 => t1.Distance + t2.Distance)).Any(d => d > 20)Selectis anIEnumerable, butAnyrequires a predicate that returns abool.