【问题标题】:C# select multiple elements with length conditionC#选择具有长度条件的多个元素
【发布时间】:2014-09-20 14:45:38
【问题描述】:

我有一个包含字符串的列表,我想要一些提示/帮助如何选择多个元素,以便所选元素的总长度为例如13 长。

我有一个想法,使用 linq 可能是一个很好的解决方案,但我还没有真正进入 linq。

提前致谢:)

这是我在发布之前尝试过的一些代码。但是由于该文件包含 +2500 行,因此需要很长时间。

List<string> textList = new List<string>(File.ReadAllLines(@"D:\text"));
List<string> newTextList = new List<string>();
foreach (string x in textList)
{
    foreach (string y in textList)
    {
        if ((x + y).Length == 13)
        {
                newTextList.Add(x + " " + y);
        }
    }
}

这里是代码的重写:

List<string> textList = new List<string>(File.ReadAllLines(@"D:\text"));
List<string> newTextList = new List<string>();
for (int i = 1; i <= 12; i++)
{
    List<string> list1 = new List<string>(textList.Where(x => x.Length == i));    
    List<string> list2 = new List<string>(textList.Where(x => x.Length == 13-i));
    foreach (string x in list1)
    {
        foreach (string y in list2)
        {
            newTextList.Add(x + " " + y);
        }
    }
}

有没有办法在下面做这样的事情?

List<string> list1 = new List<string>(textList.Where(x,y => x.Length + y.Lenght == 13)); 

感谢您的反馈。

【问题讨论】:

  • 尝试并发布。这是接收“提示/帮助”的最低要求
  • 你能举一个很好的例子来说明你想要达到的目标吗?
  • 这个问题似乎是题外话,因为它是一个代码请求。
  • 你需要第一组这样的元素还是所有的组合?
  • @VMAtm 基本上所有的组合。

标签: c# linq list select conditional-statements


【解决方案1】:

你可以试试这样的:

int currentLength=0;
var items = list.TakeWhile(x => (currentLength += x.Length ) <= 13);

【讨论】:

  • 捕获currentLength 变量警告,代码可能无法正常工作,具体取决于框架版本
  • @Melnikovl 感谢您的评论。我不知道。您能否给我一个链接,我可以在其中阅读更多相关信息。非常感谢您提前。一旦我得到你的链接,我会删除我的帖子。
  • 对不起,代码没问题,关闭不影响这段代码
猜你喜欢
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多