How to merge two collections into one

杀马特。学长 韩版系。学妹 提交于 2019-12-23 17:39:02

问题


I have two collections created within Silverlight each collection is created at separate times by different methods.

Method 1 creates a List<> titled person ( contains fields first name, last name age)

Method 2 created a List<> titled Phone ( contains phone number, cell number)

Is there a way within SL to combine these two Lists into one Collection that could then be bound to the view for display?

Example: combined into a collection that contained all properties (first name, last name age, phone number, cell number)


回答1:


You're looking for the Zip function. It allows you to combine 2 collections into a single one by combining the elements of eache.

List<Type1> col1 = ...;
List<Type2> col2 = ...;
var combined = col1.Zip(col2, (x, y) => new {
  FirstName = x.FirstName,
  LastName = x.LastName,
  PhoneNumber = y.PhoneNumber,
  CellNumber = y.CellNumber });

I'm not sure if Zip is available on not in Silverlight. If not then here's a definition of it

public static IEnumerable<TRet> Zip<T1, T2, TRet>(
  this IEnumerable<T1> enumerable1, 
  IEnumerable<T2> enumreable2,
  Func<T1, T2, TRet> func) {

  using (var e1 = enumerable1.GetEnumerator()) {
    using (var e2 = enumerable2.GetEnumerator()) {
      while (e1.MoveNext() && e2.MoveNext()) {  
        yield return func(e1.Current, e2.Current);
      }
    }
  }
}


来源:https://stackoverflow.com/questions/7536856/how-to-merge-two-collections-into-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!