重集合中找出最相近的一个数字
生活随笔
收集整理的這篇文章主要介紹了
重集合中找出最相近的一个数字
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.網(wǎng)友提供代碼
1 private static decimal getNear(List<decimal> num, decimal target) 2 { 3 List<decimal> c = new List<decimal>(); 4 foreach (var item in num) 5 { 6 c.Add(Math.Abs(item - target)); 7 } 8 c.Sort(); 9 for (int i = 0; i < num.Count; i++) 10 { 11 if (Math.Abs(num[i] - target) == c[0]) 12 { 13 return num[i]; 14 } 15 } 16 return 0; 17 }2.改進(jìn)后的代碼
1 private static decimal GetNear(List<decimal> collection, decimal target) 2 { 3 return collection.FirstOrDefault(item => Math.Abs(item - target) == collection.Select(s => Math.Abs(s - target)).OrderBy(o => o).First()); 4 }?
轉(zhuǎn)載于:https://www.cnblogs.com/liuxiaoji/p/4754777.html
總結(jié)
以上是生活随笔為你收集整理的重集合中找出最相近的一个数字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Groovy开发语言
- 下一篇: Android API Guides