Linq: Ignore non joinable items from two lists without throwing error?
In the code below, the two lists are joined on Index. But either list could have more items than the other and i just want to join up to the list with the least items and throw 开发者_C百科the rest out from the other list. So, if list 1 has 5 items and list 2 has 7 items, I want to join both up to item 5, and ignore list 2's remaining items. (and vice versa)
var joinLbxs = lbxShtCols.Items
.Cast<ListItem>()
.Select((xlFldList, index) => new
{
xlFldList,
tblFldList = lbxSqlTablesCols.Items[index]
});
Zip is not too complicated to implement by yourself.
public static IEnumerable<TResult> Zip<TSource, TOther, TResult>(
this IEnumerable<TSource> source,
IEnumerable<TOther> other,
Func<TSource, TOther, TResult> resultSelector)
{
using (var e1 = source.GetEnumerator())
{
using (var e2 = other.GetEnumerator())
{
while (e1.MoveNext() && e2.MoveNext())
{
yield return resultSelector(e1.Current, e2.Current);
}
}
}
}
As @Steven suggested in a comment, if you are using .Net 4.0, use the Zip()
method. If you don't, you could use MoreLinq to provide the same functionality.
Or you could do it yourself (assuming both lists are IList<T>
and have fast indexer):
from i in Enumerable.Range(0, new[] { list1.Count, list2.Count }.Min())
select new
{
item1 = list1[i],
item2 = list2[i]
}
Try intersecting the 2 lists; that'll give you the common items. Take()
the number smallest of the 2 lists that you want. It's not clear whether you know which list would have the smallest (by convention), so decide that beforehand. Optionally sort the list if you need BEFORE the Take()
.
int numToTake = (lbxShtCols.Count >= lbxSqlTablesCols.Count)
?lbxShtCols.Count
:lbxSqlTablesCols.Count;
var commons = lbxShtCols.Intersect(lbxSqlTablesCols)
.Take(numToTake);
精彩评论