如何修剪 List那么前面和后面的空白行被删除了吗?

发布于 2024-08-23 03:39:21 字数 832 浏览 6 评论 0原文

最简单的方法是什么?

结果应该是:

1: one
2: two
3: 
4:
5: five

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLines8833
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lines = new List<string>();
            lines.Add("");
            lines.Add("one");
            lines.Add("two");
            lines.Add("");
            lines.Add("");
            lines.Add("five");
            lines.Add("");
            lines.Add("");

            lines.TrimList();
        }
    }

    public static class Helpers
    {
        public static List<string> TrimList(this List<string> list)
        {
            //???
        }
    }
}

What is the easiest way to do this?

The results should be:

1: one
2: two
3: 
4:
5: five

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLines8833
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> lines = new List<string>();
            lines.Add("");
            lines.Add("one");
            lines.Add("two");
            lines.Add("");
            lines.Add("");
            lines.Add("five");
            lines.Add("");
            lines.Add("");

            lines.TrimList();
        }
    }

    public static class Helpers
    {
        public static List<string> TrimList(this List<string> list)
        {
            //???
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

狼性发作 2024-08-30 03:39:21

好的,现在我明白了想要的结果:

public static class Helpers
{
    // Adjust this to use trimming, avoid nullity etc if you you want
    private static readonly Predicate<string> 
        NonBlankLinePredicate = x => x.Length != 0;

    public static List<string> TrimList(this List<string> list)
    {
        int start = list.FindIndex(NonBlankLinePredicate);
        int end = list.FindLastIndex(NonBlankLinePredicate);

        // Either start and end are both -1, or neither is
        if (start == -1)
        {
            return new List<string>();
        }
        return list.GetRange(start, end - start + 1);
    }
}

请注意,这不会更改现有列表 - 它返回一个包含所需内容的新列表。鉴于您已为该方法指定了返回类型,但您的示例在不使用结果的情况下调用了它,因此尚不清楚您想要什么行为。就我个人而言,我更喜欢无副作用的方法,尽管可能值得更改名称:)

Okay, now I understand the desired results:

public static class Helpers
{
    // Adjust this to use trimming, avoid nullity etc if you you want
    private static readonly Predicate<string> 
        NonBlankLinePredicate = x => x.Length != 0;

    public static List<string> TrimList(this List<string> list)
    {
        int start = list.FindIndex(NonBlankLinePredicate);
        int end = list.FindLastIndex(NonBlankLinePredicate);

        // Either start and end are both -1, or neither is
        if (start == -1)
        {
            return new List<string>();
        }
        return list.GetRange(start, end - start + 1);
    }
}

Note that this doesn't change the existing list - it returns a new list with the desired content. It wasn't clear exactly what behaviour you wanted, given that you've given the method a return type, but your sample calls it without using the result. Personally I prefer non-side-effecting methods, although it may be worth changing the name :)

不美如何 2024-08-30 03:39:21

怎么样:

    public static void TrimList(this List<string> list) {
        while (0 != list.Count && string.IsNullOrEmpty(list[0])) {
            list.RemoveAt(0);
        }
        while (0 != list.Count && string.IsNullOrEmpty(list[list.Count - 1])) {
            list.RemoveAt(list.Count - 1);
        }
    }

请注意,签名已从您的示例中更改(返回类型为 void)。

What about this:

    public static void TrimList(this List<string> list) {
        while (0 != list.Count && string.IsNullOrEmpty(list[0])) {
            list.RemoveAt(0);
        }
        while (0 != list.Count && string.IsNullOrEmpty(list[list.Count - 1])) {
            list.RemoveAt(list.Count - 1);
        }
    }

Note that the signature has changed from your example (return type is void).

演多会厌 2024-08-30 03:39:21

试试这个:

public static List<string> TrimList(this List<string> list)  
    {  
        return list.SkipWhile(l => String.IsNullOrEmpty(l)).Reverse().SkipWhile(l => String.IsNullOrEmpty(l)).Reverse();
    } 

Try this one:

public static List<string> TrimList(this List<string> list)  
    {  
        return list.SkipWhile(l => String.IsNullOrEmpty(l)).Reverse().SkipWhile(l => String.IsNullOrEmpty(l)).Reverse();
    } 
失与倦" 2024-08-30 03:39:21

我知道老问题,但这里有一个扩展方法,它将使用 Linq 基于布尔委托从集合的开头和结尾修剪对象。

public static class IEnumerableExtensions
{
    public static IEnumerable<T> Trim<T>( this IEnumerable<T> collection, Func<T, bool> trimCondition )
    {
          return collection.SkipWhile( trimCondition ).Reverse().SkipWhile( trimCondition ).Reverse();
    }
}

您的案例示例:

lines.Trim(line => string.IsNullOrEmpty(line)); 

Old Question I know, but here is an extension method that will trim objects from the beginning and end of a collection based on a boolean delegate using Linq.

public static class IEnumerableExtensions
{
    public static IEnumerable<T> Trim<T>( this IEnumerable<T> collection, Func<T, bool> trimCondition )
    {
          return collection.SkipWhile( trimCondition ).Reverse().SkipWhile( trimCondition ).Reverse();
    }
}

Example for your case:

lines.Trim(line => string.IsNullOrEmpty(line)); 
念三年u 2024-08-30 03:39:21

如果您想删除空字符串,您可以执行以下操作...

lines = lines.Where(s => ! string.IsNullOrEmpty(s)).ToList();

更新: 抱歉,刚刚看到您的编辑,您希望保留内部空白。

在这种情况下,我只想使用一种扩展方法,就像您上面提到的那样,因为我认为没有更简单的方法可以做到这一点。

If you wanted to remove the empty strings you could do something like this...

lines = lines.Where(s => ! string.IsNullOrEmpty(s)).ToList();

Update: Sorry just seen your edit that you want internal blanks to remain.

In this case I would just an extension method like the one you mention above as I don't think there is a simpler way of doing it.

べ繥欢鉨o。 2024-08-30 03:39:21

没有内置任何东西可以执行类似的特定操作。您可以从头到尾检查项目并删除空字符串。为了最大限度地减少对列表的操作(重复使用RemoveAt删除第一个项目效率相当低),首先计算要删除的项目数量,然后使用RemoveRange方法一次性删除它们。

为了匹配您在代码中使用该方法的方式,扩展必须更改列表而不是返回新列表。

public static void TrimList(this List<string> list) {
  int cnt = 0;
  while (cnt < list.Count && list[cnt].Length == 0) cnt++;
  if (cnt > 0) list.RemoveRange(0, cnt);
  cnt = 0;
  while (cnt < list.Count - 1 && list[list.Count - cnt - 1].Length == 0) cnt++;
  if (cnt > 0) list.RemoveRange(list.Count - cnt, cnt);
}

There is nothing built in to do something specific like that. You can check the items from the beginning and end and remove the empty strings. To minimise the operations on the list (using RemoveAt repeatedly to remove the first item is rather inefficient), first count the number of items to remove and then use the RemoveRange method to remove them all at once.

To match how you use the method in the code, the extension has to alter the list rather than returning a new list.

public static void TrimList(this List<string> list) {
  int cnt = 0;
  while (cnt < list.Count && list[cnt].Length == 0) cnt++;
  if (cnt > 0) list.RemoveRange(0, cnt);
  cnt = 0;
  while (cnt < list.Count - 1 && list[list.Count - cnt - 1].Length == 0) cnt++;
  if (cnt > 0) list.RemoveRange(list.Count - cnt, cnt);
}
千纸鹤 2024-08-30 03:39:21
    int start = stringList.FindIndex((i => i.Trim() != ""));
    int end = stringList.FindLastIndex((i => i.Trim() != ""));
    List<string> range = new List<string>();
    if(start != -1 && end != -1)
        range = stringList.GetRange(start, (end - start + 1));
    int start = stringList.FindIndex((i => i.Trim() != ""));
    int end = stringList.FindLastIndex((i => i.Trim() != ""));
    List<string> range = new List<string>();
    if(start != -1 && end != -1)
        range = stringList.GetRange(start, (end - start + 1));
蓝眸 2024-08-30 03:39:21

有时,从可读性和性能角度来看,老旧的 foreach 都胜过 linq:

public static List<string> TrimList(this List<string> list)
{
    list.TrimListStart();
    vat l = list.Reverse().ToList();
    l.TrimListStart();
    return l;
}

public void TrimListStart(this List<string> list)
{
    foreach(var s in new List(list))
    {
        if(string.string.IsNullOrWhiteSpace(s))
        {
            list.Remove(s);
        }
        else
        {
            break;
        }
    }
}

Sometime the good old foreach beats linq both from the readability and performance perspective:

public static List<string> TrimList(this List<string> list)
{
    list.TrimListStart();
    vat l = list.Reverse().ToList();
    l.TrimListStart();
    return l;
}

public void TrimListStart(this List<string> list)
{
    foreach(var s in new List(list))
    {
        if(string.string.IsNullOrWhiteSpace(s))
        {
            list.Remove(s);
        }
        else
        {
            break;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文