【问题标题】:Projecting strings from a list从列表中投影字符串
【发布时间】:2013-10-23 13:38:37
【问题描述】:

我有一个字符串列表,每个字符串的长度都是可变的。我想从列表中投影一个子集,该子集的字符串从原始列表连接起来,长度等于 5。我正在使用聚合函数,但它没有给我想要的结果。对于这个投影,什么是合适的 LINQ 查询?你能帮忙吗?

代码:

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items = new List<string> {"abc", "ab", "abcd", "abcde", "abcdef", "a", "ab", "cde"};

        //All combinations of concatenations equal to length 5.
        //Only need to process an item once and need to concatenate 2 items and no more

        var filteredList = items.Where(x => x.Length < 5)
                                .Aggregate(Execute).ToList();

        foreach (var f in filteredList)
        {
            //Should out put : abc+ab = abcab
            //Should out put : abcde
            //Should out put : abcd+a = abcda
            //Should out put : ab+cde = abcde
            Console.WriteLine(f);
        }
    }

    private static string Execute(string a, string b)
    {
        if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
            return null;

        if ((a.Length + b.Length) == 5)
            return a + b;

        return null;
    }
}

几点:

  • 一旦处理了一个项目,我不需要再次考虑该项目的组合

  • 以上是真的,直到我在列表中再次找到相同的项目,一旦我找到它,我应该尝试将它与之前连接中未使用的另一个项目连接。

  • 不需要是LINQ,我只是在寻找解决方案。

  • 输出不能包含两个以上的字符串? (a + bc + de) 不是必需的。

  • 项目不需要与自身连接。

  • 我在问题中提到了输出。

注意:使用 .NET 3.5(但如果可能,也希望看到 .NET 4.0 中的快捷方式)

【问题讨论】:

  • 我不确定我是否理解这个要求。为什么 ababc (ab + abc) 不是理想的输出?
  • 因为 abc+ab 已经产生了输出,然后就不需要再考虑 abc 和 ab 了,直到找到下一个 abc 或 ab。
  • 我认为您正在寻找过滤列表的cross join 本身,而不是Aggregate 调用(假设“所有组合”表示所有组合:))
  • 必须是linq吗?
  • 输出是否可以包含两个以上的字符串? (a + bc + de)

标签: c# linq


【解决方案1】:
        List<string> items = new List<string> { "abc", "ab", "abcd", "abcde", "abcdef", "a", "ab", "cde" };
        var result = items
                        .SelectMany((x, i) => items.Skip(i + 1).Concat(new[] {string.Empty}), (s1, s2) => s1 + s2)
                        .Where(s => s.Length == 5);

【讨论】:

  • 为什么是.Take(items.Count - i - 1)?看起来您特别排除了最后一个元素。
  • 糟糕...实际上我想排除当前元素,以免将其与自身连接。所以我用 Skip(i + 1) 替换了 Skip(i)... 而且我不排除最后一个元素!谢谢你的评论!
  • 好的,我明白了。在这种情况下,Take 是多余的,因为默认情况下,IEnumerable 将枚举所有剩余的元素。
【解决方案2】:

使用双 for 循环同时跟踪哪些索引给出了匹配应该这样做:

IEnumerable<string> items = new List<string> { "abc", "ab", "abcd", "abcde", "abcdef", "a", "ab", "cde" };
var filteredList = GimmeFives(items).ToList();

private IEnumerable<string> GimmeFives(IEnumerable<string> items)
{
    //"Once an item is processed, I dont need to consider that item again for a combination"
    var indexesProcessed = new List<int>();

    for (int i = 0; i < items.Count(); i++)
    {
        if (indexesProcessed.Contains(i)) { continue; }

        var first = items.ElementAt(i);
        if (first.Length == 5)
        {
            yield return first;
        }
        else
        {
            //Start the second loop after index "i", to avoid including previously processed items:
            for (int j = i+1; j < items.Count(); j++)
            {
                if (indexesProcessed.Contains(j)) { continue; }

                var second = items.ElementAt(j);

                if ((first.Length + second.Length) == 5)
                {
                    //Remove the middle "+" sign in production code...
                    yield return (first + "+" + second);

                    indexesProcessed.Add(i);
                    indexesProcessed.Add(j);

                    //"Once an item is processed, I dont need to consider that item again for a combination"
                    //"first" has gotten its match, so we don't need to search for another "second":
                    break;
                }
            }
        }

    }
}

输出:

abc+ab
abcd+a
abcde
ab+cde

【讨论】:

    【解决方案3】:
    void Main()
    {
        var items = new List<string> {"abc", "ab", "abcd", "abcde", "abcdef", "a", "ab", "cde"};
        bool[] flag=new bool[items.Count()];
        var output=items.SelectMany((x,i)=>items.Select((y,j)=>concat(flag,items,i,j)))
                        .Where(x=>x!="");
    }
    
    public string concat(bool[] flag,List<string> items,int i,int j)
    {
    if(flag[i]==false && flag[j]==false && (items[i].Length==5||(items[i]+items[j]).Length==5))
    {
          flag[i]=true;
          flag[j]=true;
    
          if(i==j)return items[i];
          else return items[i]+","+items[j];
    }
    else return "";
    }
    

    输出:

    abc,ab 
    abcd,a 
    abcde 
    ab,cde 
    

    【讨论】:

    • 这提供了与它们自身连接的项目。目前尚不清楚它们是否应该被包括在内或排除在外。这也不会显示示例中的单个字符串值;它只显示对。
    • 不,你错过了最后一个,即 ab+cde。正如我所说,如果该项目再次出现,则应予以考虑。
    • 我说过,如果一个项目被处理了,就不需要再考虑它了。例如 abc+ab = abcab(现在使用 abc 和 ab),这意味着 abc 不应出现在另一个串联中。
    【解决方案4】:

    如果你问我,我会说:“不要偷懒”。

        private static List<string> ValidCombinationsFind(List<string> iSource)
        {
            List<string> lstResult = new List<string>();
    
            //Use and explicit mask to remember indexes in iSource which were used.
            bool[] ablnUsageMask = new bool[iSource.Count];
    
            int intCurrentIndex = 0;
    
            //Examine the source list one by one.
            while (intCurrentIndex < iSource.Count - 1)
            {
                //If the next item is not already used then go on.
                if (!ablnUsageMask[intCurrentIndex])
                {
                    string strCurrentItem = iSource[intCurrentIndex];
    
                    //If the item is ok then check every remaining item for a match.
                    if (!string.IsNullOrEmpty(strCurrentItem))
                    {
                        //Check if an item fits on its own.
                        if (strCurrentItem.Length == 5)
                        {
                            ablnUsageMask[intCurrentIndex] = true;
                            lstResult.Add(strCurrentItem);
                        }
                        else
                        {
                            for (int intNextItemIndex = intCurrentIndex + 1; intNextItemIndex < iSource.Count; intNextItemIndex++)
                            {
                                //If the next item is not already used then go on.
                                if (!ablnUsageMask[intNextItemIndex])
                                {
                                    string strNextItem = iSource[intNextItemIndex];
    
                                    if (!string.IsNullOrEmpty(strNextItem))
                                    {
                                        if ((strCurrentItem.Length + strNextItem.Length) == 5)
                                        {
                                            ablnUsageMask[intCurrentIndex] = true;
                                            ablnUsageMask[intNextItemIndex] = true;
                                            lstResult.Add(strCurrentItem + strNextItem);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
    
                intCurrentIndex++;
            }
    
            return lstResult;
        }
    

    【讨论】:

    • 它没有输出任何输出
    • 已修复,谢谢。我忘记放了!在 string.IsNullOrEmpty 之前。
    【解决方案5】:

    所以这里的想法是配对对象,使这两个对象具有完全正确的大小。我们可以在这里做的是按大小对所有字符串进行分组。我们知道,1号和4号的物品都需要配对,2号和3号的需要配对,5号的单品就可以了。

    因此,我们可以遍历可能的尺寸,获取具有该尺寸的组和具有该尺寸的组以创建所需的项目,然后将这两个集合拉上拉链。对于每个索引,Zip 将从第一个组中取出第一个项目,将其与第二个组中的第一个项目匹配,然后依此类推。这意味着每个字符串将永远不会重复。然后我们可以在末尾添加大小正好合适的项目。

    private static IEnumerable<string> MakeDesiredSize(
        List<string> items, int desiredSide)
    {
        var lookup = items.Where(item => item.Length <= desiredSide)
            .ToLookup(item => item.Length);
        return Enumerable.Range(1, desiredSide / 2)
                .SelectMany(i => lookup[i].Zip(lookup[desiredSide - i]
                    , (a, b) => a + b))
                .Concat(lookup[desiredSide]);
    }
    

    由于您使用的是 3.5,因此这里是 Zip 的实现:

    public static IEnumerable<TResult> Zip<TSource, TResult>(
        this IEnumerable<TSource> first,
        IEnumerable<TSource> second,
        Func<TSource, TSource, TResult> resultSelector)
    {
        using (var itOne = first.GetEnumerator())
        using (var itSecond = second.GetEnumerator())
            while (itOne.MoveNext() & itSecond.MoveNext())
                yield return resultSelector(itOne.Current, itSecond.Current);
    }
    

    【讨论】:

    • .NET 3.5 中 Zip 的替代方案是什么
    • @Mike 重新实现它;写起来很简单。只需接受这两个序列,同时迭代它们并在当前项上产生选择器的结果。
    • @Mike 我在运行代码时得到了与您的问题完全相同的组合。请注意,根据您给出的要求,有许多不同的可能解决方案都是有效的,具体取决于哪些项目选择与哪些项目匹配,以及您选择显示项目对的顺序。如果在这些不同选项中获得一个特定解决方案很重要,则需要指定如何确定哪些匹配项是正确的。旁注,如果您将Zip 更改为使用(a, b) =&gt; a + "+" + b),则可以清楚地了解组合是什么。
    • 程序为我输出aabcd、abcbc、abcde和abcde。
    • @Mike 我有ababc 用于第二项。你确定这不是你得到的吗?鉴于这种变化,每个项目都与您拥有的对完全对应,它只是具有不同顺序的组合。我的第一个是你的第三个,但是项目颠倒了,我的第二个是你的第一个,我的第三个是你的第四个,我的第四个是你的第二个。鉴于您提供的规则,这是两种不同但同样有效的解决方案。
    【解决方案6】:

    我相信这可以满足您的需求:

      var filteredList = items.Where(x => x.Length < 5)
        .SelectMany(x => items, (y, z) => { return Execute(y, z); })
        .Where(x => x != null).Distinct().ToList();
    

    【讨论】:

    • 这包括 (ab + abc) 和 (abc + ab)。只有其中一个应该出现在输出中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2022-12-01
    • 2015-12-19
    • 1970-01-01
    • 2019-07-21
    • 2013-05-31
    相关资源
    最近更新 更多