Home > Blockchain >  C# Linq find unique item
C# Linq find unique item

Time:06-02

I'm looking for a way to find items in a list that are unique:

List<Item> list = new List<Item>();
list.Add(new Item() { id = 1, name = "test" });
list.Add(new Item() { id = 2, name = "test" });
list.Add(new Item() { id = 3, name = "test1"});
list.Add(new Item() { id = 4, name = "test2"});
list.Add(new Item() { id = 5, name = "test2"});

var uniqueItems = ?

uniqueItems should contain { id = 3, name = "test1"} because test1 is unique

Whats the best way to implement that?

CodePudding user response:

list.GroupBy(x => x.Name)
    .Where(x => x.Count() == 1)
    .Select(x => new Item { id = x.First().id, name = x.Key });

CodePudding user response:

Several ways (using Linq):

var uniqueItems = list.Where(item => list.Count(li => String.Equals(item.name, li.name)) == 1);

//or

var uniqueItems = list
    .GroupBy(item => item.name)
    .Where(g => g.Count() == 1)
    .SelectMany(g => g);

CodePudding user response:

You could use the linq operators Where and Count like

var uniqueItems = list.Where(x => list.Count(item => item.name == x.name) == 1);
  • Related