Filtering lists using LINQ

前端 未结 9 2057
暖寄归人
暖寄归人 2021-02-04 00:23

I\'ve got a list of People that are returned from an external app and I\'m creating an exclusion list in my local app to give me the option of manually removing people from the

相关标签:
9条回答
  • 2021-02-04 00:47

    I couldn't figure out how to do this in pure MS LINQ, so I wrote my own extension method to do it:

    public static bool In<T>(this T objToCheck, params T[] values)
    {
        if (values == null || values.Length == 0) 
        {
            return false; //early out
        }
        else
        {
            foreach (T t in values)
            {
                if (t.Equals(objToCheck))
                    return true;   //RETURN found!
            }
    
            return false; //nothing found
        }
    }
    
    0 讨论(0)
  • 2021-02-04 00:51

    This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.

    List<Person> filteredResults =from p in people
            join e in exclusions on p.compositeKey equals e.compositeKey into temp
            from t in temp.DefaultIfEmpty()
            where t.compositeKey == null
            select p
    

    let me know if it works!

    0 讨论(0)
  • 2021-02-04 00:52

    I would do something like this but i bet there is a simpler way. i think the sql from linqtosql would use a select from person Where NOT EXIST(select from your exclusion list)

    static class Program
    {
        public class Person
        {
            public string Key { get; set; }
            public Person(string key)
            {
               Key = key;
            }
        }
        public class NotPerson
        {
            public string Key { get; set; }
            public NotPerson(string key)
            {
               Key = key;
            }
        }
        static void Main()
        {
    
           List<Person> persons = new List<Person>()
           { 
               new Person ("1"),
               new Person ("2"),
               new Person ("3"),
               new Person ("4")
           };
    
           List<NotPerson> notpersons = new List<NotPerson>()
           { 
               new NotPerson ("3"),
               new NotPerson ("4")
           };
    
           var filteredResults = from n in persons
                                 where !notpersons.Any(y => n.Key == y.Key)
                                 select n;
    
           foreach (var item in filteredResults)
           {
              Console.WriteLine(item.Key);
           }
        }
     }
    
    0 讨论(0)
提交回复
热议问题