I want do Linq like in topic. I have List<double>
i want to check there is 2
different double
which sum
is more then for example 20
. i don't have idea how to do that. I create something like this
tags.Any(x => (x.Distance + tags.Select(y => y.Distance).First() > 20));
But it check only with first object, and check with myself. If 2
elements on list are the same they can be check, but with myself can't.
Can i do something like take this and next object from list?
var tags = new List<double>() {
5, 7, 9, 13
};
if ((i != j) && (tags(i) + tags(j)) > 20)
{
}
This link should work like this if
when it would be array in a loop .
Try Cartesian Join ( tags
with itself ):
var tags = new List<double>() {
5, 7, 9, 13
};
var result = tags
.Select((a, index_a) => tags
.Where((b, index_b) => index_a != index_b && a + b > 20)
.Select(b => Tuple.Create(a, b)))
.SelectMany(item => item);
// Let's have a look:
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
(9, 13)
(13, 9)
if you don't want (13, 9)
and alike pairs (where index_a > index_b
)
var result = tags
.Select((a, index_a) => tags
.Skip(index_a + 1)
.Where(b => a + b > 20)
.Select(b => Tuple.Create(a, b)))
.SelectMany(item => item);
// Let's have a look:
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
(9, 13)
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.
eg
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
*/
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.