给定一个整数数组(+ ve和-ve数是无序的), 什么是LINQ语句来查找总和最接近0的两个数字
E.g int[] a = new int[]{2, 56, -11, 15, 12, 10, 43, -59, -13}
在上面的整数集{-11
,10
}和{12
中,-13
}是两个最接近{{1}的整数}}
除了LINQ的以下基本查询之外,我无法得到太多,因为我不知道如何继续,
0
答案 0 :(得分:1)
如果它可以是集合中的任何两个值,那么你可以这样做......
var set = new int[] { 2, 56, -11, 15, 12, 10, 43, -59, -13 };
var ret = (from a in set
from b in set
orderby Math.Abs(a + b)
select new
{
a,
b
}).First();
Console.WriteLine(ret); // {a: -11, b:12 }
如果你想要对大型集合稍微提高性能(并且可以假设混合了负值和正值),你可以这样做。
var set = new int[] { 2, 56, -11, 15, 12, 10, 43, -59, -13 };
var ret = (from a in set.Where(x => x >= 0)
from b in set.Where(y => y < 0)
orderby Math.Abs(a + b)
select new
{
a,
b
}).First();
Console.WriteLine(ret); // { a= 12, b= -11}
因为你现在想要整个匹配集,不包括与自己的匹配......
var set = new int[] { 2, 56, -11, 15, 12, 10, 43, -59, -13 };
var ret = from a in set
from b in set
where a != b
let c = new { a, b }
group c by Math.Abs(c.a + c.b);
var minset = ret.First(i => i.Key == ret.Min(j => j.Key))
.Select(s=>s);
Console.WriteLine(minset.Aggregate(new StringBuilder(),
(sb,v)=>sb.Append(v)
.AppendLine()
));
/*
{ a = -11, b = 12 }
{ a = -11, b = 10 }
{ a = 12, b = -11 }
{ a = 12, b = -13 }
{ a = 10, b = -11 }
{ a = -13, b = 12 }
*/
重复数据删除......
var set = new[] { 2, 56, -11, 15, 12, 10, 43, -59, -13 };
var ret = from a in set
from b in set
where a != b
let c = new { a, b }
group c by Math.Abs(c.a + c.b);
var minset = ret.First(i => i.Key == ret.Min(j => j.Key))
.Select(s => new { a = Math.Min(s.a, s.b), b = Math.Max(s.a, s.b) })
.Distinct();
Console.WriteLine(minset.Aggregate(new StringBuilder(),
(sb, v) => sb.Append(v)
.AppendLine()));
/*
{ a = -11, b = 12 }
{ a = -11, b = 10 }
{ a = -13, b = 12 }
*/
答案 1 :(得分:0)
var data = new [] { 2, 56, -11, 15, 12, 10, 43, -59, -13 };
// TODO : assert data.Length >= 2
var query = from i in Enumerable.Range (0, data.Length - 2)
from j in Enumerable.Range (i + 1, data.Length - 1 - i)
let x = data[i] let y = data[j]
group new { x, y } by Math.Abs (x + y) into g
orderby g.Key select g;
Console.WriteLine (string.Join ("\n", query.First ()));
{x = -11,y = 12}
{x = -11,y = 10}
{x = 12,y = -13}