我这里有一些代码,只能从数组中找到第一个小数字。
public void Test() {
int[] numbers = { 121, 124, 131, 135, 219, 287, 361, 367, 382, 420 };
var onlyfirstNumbersLessThanGiven = numbers.TakeWhile(n => n < 135);
Console.WriteLine("First numbers less than ");
foreach (var n in onlyfirstNumbersLessThanGiven)
{
Console.WriteLine(n);
}
}
如何从上面的阵列中找到131?请帮帮我
答案 0 :(得分:7)
这个怎么样?
有序数组:
@NgModule({
declarations: [
AppComponent,
// other application-specific components...
PageNotFoundComponent,
],
imports: [
BrowserModule,
CommonModule,
ReactiveFormsModule,
MdButtonModule,
// other MD modules...
MdTooltipModule,
OverlayModule,
PortalModule,
RtlModule,
routing // application routing
],
providers : [
Title,
MdIconRegistry,
// set of application-specific providers...
],
entryComponents: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {
}
无序数组:
numbers.LastOrDefault(x => x < 135);
答案 1 :(得分:3)
尽管Renan的回答完全正确,为什么不直接使用First(),编辑或TakeWhile()和Last()?
e.g。
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 435, 67, 12, 19 };
int first = numbers.First(number => number > 80);
int firstSmaller = numbers.TakeWhile(number => number < 80).Last(); // returns 65 since its the first one smaller than 80 in the series
Console.WriteLine(first);
并将其与您的情况相匹配:
public void Test() {
int[] numbers = { 121, 124, 131, 135, 219, 287, 361, 367, 382, 420 };
var onlyfirstNumbersLessThanGiven = numbers.TakeWhile(n => n < 135).Last();
Console.WriteLine("First numbers less than ");
Console.WriteLine(onlyfirstNumbersLessThanGiven);
}
有一些限制:假定数组已排序,并且必须按升序排列。
感谢 Ivan Stoev 指出我的错误
答案 2 :(得分:2)
找到号码本身,因为你知道你想要的号码,你不需要任何范围。
numbers.Where(x => x == 131);
答案 3 :(得分:0)
此示例有助于清除。
public void Test()
{
int [] numbers = {121,324,431,135,119,287,361,367,382,420};
var OFNLTG = numbers.Where(x =&gt; x&lt; 121).Max();
Console.WriteLine(“First Max Number:”);{ Console.WriteLine(OFNLTG);
}
}