有没有机会使用Linq(C#)获得独特的记录?

时间:2009-04-07 07:23:28

标签: c# linq unique

我得到了list<list<string>>

list[x][0]中的

是我想从中选择唯一记录的记录,因此这样的记录不会出现在任何其他list[x][0]中,当我选择它时,我想要整行{{1被选中。我没有在Linq找到适当的例子,请帮忙:(

修改

当Jon Skeet要求我澄清时,我不能否认; - )

list[x]

包含字符串表的列表。每个字符串“table”都包含几个键list<list<string>> ,我想从list-&gt;中获取唯一的记录。意思是“表”中的第一项。

因此:

list[x][several_items]

- &GT; unique将意味着我可以将行item[0] = "2","3","1","3" item[1] = "2","3","4","2" item[3] = "10","2" item[4]= "1","2" 派生为唯一的。因为第一次出现数字/字符串很重要。

如果列表中有两个或更多记录/行(item[3] and item[4]存在多次,则它不是唯一的。

每个列表的第一个元素对于确定唯一性很重要。也许如果有人可以帮助找到一种找到非独特的方法,那就更容易了 - &gt;所以从上面的例子中我只得到item [0]和item [1]

6 个答案:

答案 0 :(得分: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;
    }
}

编辑:好的,如果您只关心列表中第一个唯一性元素,我们需要稍微改变一下:

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;
    }
}

你打电话给:

list.UniqueBy(row => row[0])

答案 1 :(得分:2)

也许是这样的事情?

我现在相当确定这会对你有用,给出你的澄清:)

var mylist = new List<List<string>>() {
    new List<string>() { "a", "b", "c" },
    new List<string>() { "a", "d", "f" },
    new List<string>() { "d", "asd" },
    new List<string>() { "e", "asdf", "fgg" }
};
var unique = mylist.Where(t => mylist.Count(s => s[0] == t[0]) == 1);

unique现在包含上面的“d”和“e”条目。

答案 2 :(得分:2)

以下是您需要的代码。它非常适合我选择只有不同的值。

//distinct select in LINQ to SQL with Northwind
var myquery = from user in northwindDC.Employees
              where user.FirstName != null || user.FirstName != ""
              orderby user.FirstName
              group user by user.FirstName into FN
              select FN.First();

答案 3 :(得分:1)

这是给你的一些Linq。

List<List<string>> Records = GetRecords();
//
List<List<string> UniqueRecords = Records
  .GroupBy(r => r[0])
  .Where(g => !g.Skip(1).Any())
  .Select(g => g.Single())
  .ToList();

答案 4 :(得分:0)

您可以维护一个列表和索引/ dictionary

List<List<string>> values;
Dictionary<string, List<string>> index;

将值添加到值时,还可以将List添加到索引中,并将字符串作为索引。

values[x].Add(newString);
index[newString] = values[x];

然后你可以通过以下方式获得正确的清单:

List<string> list = index[searchFor]

在构建索引时,你会失去一些(最小的)性能和内存,但是在检索数据时你会获得很多。

如果字符串不唯一,您还可以存储List&gt;在dictionary /索引中,允许每个索引键有多个结果。

很抱歉没有Linq,这看起来不那么酷,但你有快速查找,而恕我直言,查找代码更清晰。

答案 5 :(得分:0)

我会继续把这个添加到战斗中。

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            List<string> xx = new List<string>() { "xx", "yy", "zz" };
            List<string> yy = new List<string>() { "11", "22", "33" };
            List<string> zz = new List<string>() { "aa", "bb", "cc" };
            List<List<string>> x = new List<List<string>>() { xx, yy, zz, xx, yy, zz, xx, yy };
            foreach(List<string> list in x.Distinct()) {
                foreach(string s in list) {
                    Console.WriteLine(s);
                }
            }
        }
    }
}