[英]System.ArgumentOutOfRangeException linq c#
I have to make a program that takes the domain for each columns. 我必须编写一个程序,以每列的域。
My code is this, but when i want show throws an exception (System.ArgumentOutOfRangeException). 我的代码是这样,但是当我想播放时抛出异常(System.ArgumentOutOfRangeException)。
string[] all_lines = { "1, 2, 3" , "4, 5, 6", "4, 2, 3", "4, 2, 6", "9, 8, 7" };
string[] separator = new string[] { ", " };
int nAtt = all_lines[0].Split(separator, StringSplitOptions.RemoveEmptyEntries).Count() ;
List<IEnumerable> dom = new List<IEnumerable>();
for (int i = 0; i < nAtt; i++)
{
var ele = (from lines in all_lines
let data = lines.Split(separator, StringSplitOptions.RemoveEmptyEntries)
select data.ElementAt(i)).Distinct();
dom.Add(ele);
}
foreach (var row in dom)
{
Console.Write("( ");
foreach (var ele in row)
Console.Write("{0} ", ele);
Console.WriteLine(")");
}
The output of this code should be: 此代码的输出应为:
( 1 4 9 )
(1 4 9)
( 2 5 8 )(2 5 8)
( 3 6 7 )(3 6 7)
Is there any solution or alternative for this? 有没有解决方案或替代方案?
There is closure problem. 有关闭问题。 see
ElementAt(i)
here. 在这里看到
ElementAt(i)
。
for (int i = 0; i < nAtt; i++)
{
var ele = (from lines in all_lines
let data = lines.Split(separator, StringSplitOptions.RemoveEmptyEntries)
select data.ElementAt(i)).Distinct();
dom.Add(ele);
}
This query will use the variable i
it self. 这个查询将使用变量
i
它的自我。 its not a copy. 它不是副本。 so after loop finishes
i
becomes nAtt
and you get exception when you try to use it. 因此,在循环完成后,
i
变成nAtt
并且在尝试使用它时会遇到异常。 so you have to store variable before using it. 因此您必须先存储变量,然后再使用它。
var i1 = i;
var ele = (from lines in all_lines
let data = lines.Split(separator, StringSplitOptions.RemoveEmptyEntries)
select data.ElementAt(i1)).Distinct();
dom.Add(ele);
Your technique is terribly inefficient because, by using .Count()
and .ElementAt()
repeatedly, you are reiterating your enumerables unnecessarily, many times over. 你的技术是因为非常低效的,通过使用
.Count()
和.ElementAt()
多次,你是不必要重申你可枚举,许多倍。
A considerably more efficient, elegant and less error-prone approach might be: 一种更有效,更优雅,更不易出错的方法可能是:
var dom = all_lines
.SelectMany(line => line
.Split(new[]{", "}, StringSplitOptions.RemoveEmptyEntries)
.Select((x, i) => new{x, i}))
.GroupBy(x => x.i)
.Select(g => g.Select(gi => gi.x).Distinct())
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.