我有一个 list<list<string>>
in list[x][0]是我想要选择唯一记录的记录,因此这样的记录不会出现在任何其他记录中list[x][0,当我选择它时,我想要选择整行list[x].我没有在Linq找到适当的这个例子,请帮忙:(
编辑
当Jon Skeet要求我澄清时,我不能否认;-)
list<list<string>>
Run Code Online (Sandbox Code Playgroud)
包含字符串表的列表.每个字符串"table"包含几个键list[x][several_items],我想从list->中获取唯一记录,这意味着该"表"中的FIRST项.
从而:
item[0] = "2","3","1","3"
item[1] = "2","3","4","2"
item[3] = "10","2"
item[4]= "1","2"
Run Code Online (Sandbox Code Playgroud)
- > unique意味着我可以将行派生item[3] and item[4]为唯一的.因为第一次出现数字/字符串很重要.
如果有2个或更多记录/行(item[x] of which first item (item[x][0])在列表中存在多次,则它不是唯一的.
每个列表的第一个元素对于确定唯一性很重要.也许如果有人可以帮助找到找到非唯一的方法会更容易 - >所以从上面的例子中我只得到item [0]和item [1]
Jon*_*eet 10
编辑:我已经更新了UniqueBy底部的实现,以显着提高效率,并且只迭代源一次.
如果我理解正确(这个问题还不清楚 - 如果你能提供一个例子,那将会非常有帮助)这就是你想要的:
public static IEnumerable<T> OnlyUnique<T>(this IEnumerable<T> source)
{
// No error checking :)
HashSet<T> toReturn = new HashSet<T>();
HashSet<T> seen = new HashSet<T>();
foreach (T element in source)
{
if (seen.Add(element))
{
toReturn.Add(element);
}
else
{
toReturn.Remove(element);
}
}
// yield to get deferred execution
foreach (T element in toReturn)
{
yield return element;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:好的,如果您只关心列表中第一个唯一性元素,我们需要稍微改变一下:
public static IEnumerable<TElement> UniqueBy<TElement, TKey>
(this IEnumerable<TElement> source,
Func<TElement, TKey> keySelector)
{
var results = new LinkedList<TElement>();
// If we've seen a key 0 times, it won't be in here.
// If we've seen it once, it will be in as a node.
// If we've seen it more than once, it will be in as null.
var nodeMap = new Dictionary<TKey, LinkedListNode<TElement>>();
foreach (TElement element in source)
{
TKey key = keySelector(element);
LinkedListNode<TElement> currentNode;
if (nodeMap.TryGetValue(key, out currentNode))
{
// Seen it before. Remove if non-null
if (currentNode != null)
{
results.Remove(currentNode);
nodeMap[key] = null;
}
// Otherwise no action needed
}
else
{
LinkedListNode<TElement> node = results.AddLast(element);
nodeMap[key] = node;
}
}
foreach (TElement element in results)
{
yield return element;
}
}
Run Code Online (Sandbox Code Playgroud)
你打电话给:
list.UniqueBy(row => row[0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9980 次 |
| 最近记录: |