Feedback

LINQ-Erweiterung für eindeutige Liste

Sprache: C#

Diese Erweiterung nimmt eine Liste und ermittelt aus dieser durch Übergabe eines Schlüssels eine Liste mit eindeutigen Werten. Beispiel: [code] class Program { static void Main() { List<Person> personList = new List<Person> { new Person{Name = "Gü"}, new Person{Name = "Andrea"}, new Person{Name = "Gü"} }; List<Person> myUniqueList = personList.Unique(i => i.Name); } } public class Person { public string Name { get; set; } } [/code] Im Ergebnis werden nur eindeutige Werte in Bezug auf den Namen zurückgegeben.
using System;
using System.Collections.Generic;
using System.Linq;

namespace gfoidl.Linq
{
	public static class LinqExtensions
	{
		public static List<T> Unique<K, T>(this List<T> inputList, Func<T, K> func)
		{
			#region Input validation
			if (func == null)
				throw new ArgumentNullException("Key selector function cannot be null");

			if (inputList == null)
				return null;

			if (inputList.Count == 0)
				return new List<T>();
			#endregion

			var grp = inputList.GroupBy(func);
			return grp.Select(g => g.First()).ToList();
		}
	}
}
using System;
using System.Collections.Generic;
using System.Linq;

namespace gfoidl.Linq
{
	public static class LinqExtensions
	{
		public static List<T> Unique<K, T>(this List<T> inputList, Func<T, K> func)
		{
			#region Input validation
			if (func == null)
				throw new ArgumentNullException("Key selector function cannot be null");

			if (inputList == null)
				return null;

			if (inputList.Count == 0)
				return new List<T>();
			#endregion

			var grp = inputList.GroupBy(func);
			return grp.Select(g => g.First()).ToList();
		}
	}
}

6 Kommentare

  1. Vielleicht kommt die schlechte Bewertung auch durch das fehlerhafte Demo, was ich aber auch für ungerechtfertigt halte. Ich hab’s mal korrigiert und um die Ausgabe von myUniqueList erweitert:
    [code]class Program
    {
    static void Main()
    {
    List fooList = new List {
    new Person { Name = „Günther“ },
    new Person { Name = „Andrea“ },
    new Person { Name = „Günther“ }
    };
    List
    myUniqueList = fooList.Unique(i => i.Name);
    foreach (var person in myUniqueList)
    {
    Console.WriteLine(person.Name);
    }

    // Verhindert das selbsttätige Schließen des Konsolenfensters.
    Console.WriteLine(„nPress any key to terminate the program.“);
    Console.ReadKey();
    }
    }

    class Person
    {
    public string Name { get; set; }
    }[/code]