English 中文(简体)
如何将每两个项目从电子电子电子数据系统作为电子数据进行计算?
原标题:How take each two items from IEnumerable as a pair?

页: 1

我需要通过名单加以编辑,并创建<条码>IE 计数<Tuple<string, string>>,图尔斯将研究:

"First", "1"

"Second", "2"

So I need to create pairs from a list I have to get pairs as mentioned above.

最佳回答

http://www.un.org。

var pairs = source.Select((value, index) => new {Index = index, Value = value})
                  .GroupBy(x => x.Index / 2)
                  .Select(g => new Tuple<string, string>(g.ElementAt(0).Value, 
                                                         g.ElementAt(1).Value));

页: 1 IEvidable<Tuple<string,string>>。 它通过按其奇/7职位对各要素进行分类,然后将每个组扩大为<代码>Tuple。 《蓝色地图集》所建议的<代码>Zip办法>上的这种做法的好处是,t 仅列出了“一度的原始数字”。

然而,人们很难从头看理解,因此,我要么采取另一种方式(即不使用林吉),要么将其意图记录在使用的地方。

问题回答

达到这一目的的zy延伸方法是:

public static IEnumerable<Tuple<T, T>> Tupelize<T>(this IEnumerable<T> source)
{
    using (var enumerator = source.GetEnumerator())
        while (enumerator.MoveNext())
        {
            var item1 = enumerator.Current;

            if (!enumerator.MoveNext())
                throw new ArgumentException();

            var item2 = enumerator.Current;

            yield return new Tuple<T, T>(item1, item2);
        }
}

请注意,如果内容不算如此,就会消失。 另一种方式是利用这一推广方法将来源收集分成以下几个部分:

public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> list, int batchSize)
{

    var batch = new List<T>(batchSize);

    foreach (var item in list)
    {
        batch.Add(item);
        if (batch.Count == batchSize)
        {
            yield return batch;
            batch = new List<T>(batchSize);
        }
    }

    if (batch.Count > 0)
        yield return batch;
}

然后,你可以做到:

var tuples = items.Chunk(2)
    .Select(x => new Tuple<string, string>(x.First(), x.Skip(1).First()))
    .ToArray();

最后,只使用现有的推广方法:

var tuples = items.Where((x, i) => i % 2 == 0)
    .Zip(items.Where((x, i) => i % 2 == 1), 
                     (a, b) => new Tuple<string, string>(a, b))
    .ToArray();

http://code.google.com/p/morelinq/"rel=“noreferer”>morelinq a Batch。 推广方法,可以做你想要的事情:

var str = new string[] { "First", "1", "Second", "2", "Third", "3" };
var tuples = str.Batch(2, r => new Tuple<string, string>(r.FirstOrDefault(), r.LastOrDefault()));

您可使用LINQ .Zip()。 推广方法:

IEnumerable<string> source = new List<string> { "First", "1", "Second", "2" };
var tupleList = source.Zip(source.Skip(1), 
                           (a, b) => new Tuple<string, string>(a, b))
                      .Where((x, i) => i % 2 == 0)
                      .ToList();

Basically the approach is zipping up the source Enumerable with itself, skipping the first element so the second enumeration is one off - that will give you the pairs ("First, "1"), ("1", "Second"), ("Second", "2").

然后,我们正在过滤奇迹,因为我们不想要这些les子,最后是正确的tu(第一,“1”,第二,”2,等等。

<><>Edit>:

我实际上同意这些评论的意见——这是我考虑的“单独”法典——看着聪明,但显然(而不是如此明显) down倒:

  1. Performance: the Enumerable has to be traversed twice - for the same reason it cannot be used on Enumerables that consume their source, i.e. data from network streams.

  2. Maintenance: It s not obvious what the code does - if someone else is tasked to maintain the code there might be trouble ahead, especially given point 1.

尽管如此,我或许会使用一个良好的旧的<代码>foreach,自行选择,或作为来源收集的“<> >代码”清单。 因此,我可以直接使用该指数。

Starting from NET 6.0, you can use Enumerable.Chunk(IEnumerable, Int32)

var tuples = new[] {"First", "1", "Second", "2", "Incomplete" }
    .Chunk(2)
    .Where(chunk => chunk.Length == 2)
    .Select(chunk => (chunk[0], chunk[1]));
IEnumerable<T> items = ...;
using (var enumerator = items.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        T first = enumerator.Current;
        bool hasSecond = enumerator.MoveNext();
        Trace.Assert(hasSecond, "Collection must have even number of elements.");
        T second = enumerator.Current;

        var tuple = new Tuple<T, T>(first, second);
        //Now you have the tuple
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签