Подтвердить что ты не робот

Сравнить два списка и вернуть не соответствующие элементы, используя linq

У меня есть два списка

List<Sent> SentList;
List<Messages> MsgList;

оба имеют одно и то же свойство MsgID;

MsgList            SentList  

MsgID Content      MsgID Content Stauts
1       aaa        1       aaa     0
2       bbb        3       ccc     0
3       ccc        
4       ddd
5       eee

Я хочу сравнить MsgID в Msglist с отправленным списком и нуждаться в элементах, которые не находятся в отправленном списке, используя linq

Result 

MsgID Content
2       bbb
4       ddd
5       eee
4b9b3361

Ответ 1

Вы можете сделать что-то вроде:

HashSet<int> sentIDs = new HashSet<int>(SentList.Select(s => s.MsgID));

var results = MsgList.Where(m => !sentIDs.Contains(m.MsgID));

Это вернет все сообщения в MsgList, у которых нет идентификатора соответствия в SentList.

Ответ 2

Наивный подход:

MsgList.Where(x => !SentList.Any(y => y.MsgID == x.MsgID))

Помните, что это займет до m*n операций, поскольку он сравнивает каждый MsgID в SentList с каждым в MsgList ( "до", потому что он будет замыкаться на короткое замыкание, когда это произойдет).

Ответ 3

Хорошо, у вас уже есть хорошие ответы, но они самые Лямбда. Более подход LINQ будет похож на

var NotSentMessages =
                from msg in MsgList
                where !SentList.Any(x => x.MsgID == msg.MsgID)
                select msg;

Ответ 4

Вы можете сделать что-то вроде

var notSent = MsgSent.Except(MsgList, MsgIdEqualityComparer);

Вам нужно будет предоставить собственный сопоставитель сравнений, указанный в MSDN

http://msdn.microsoft.com/en-us/library/bb336390.aspx

Просто это равенство равенство равенства равенству только по свойству MsgID каждого соответствующего типа. Поскольку сопоставитель равенства сравнивает два экземпляра одного и того же типа, вам нужно будет определить интерфейс или общий базовый тип, который реализуется как отправленным, так и сообщением, обладающим свойством MsgID.

Ответ 5

Вы можете сделать это, это самый быстрый процесс

Var result = MsgList.Except(MsgList.Where(o => SentList.Select(s => s.MsgID).ToList().Contains(o.MsgID))).ToList();

Это даст вам ожидаемый результат.

Ответ 6

Попробуйте,

  public class Sent
{
    public int MsgID;
    public string Content;
    public int Status;

}

public class Messages
{
    public int MsgID;
    public string Content;
}

  List<Sent> SentList = new List<Sent>() { new Sent() { MsgID = 1, Content = "aaa", Status = 0 }, new Sent() { MsgID = 3, Content = "ccc", Status = 0 } };
            List<Messages> MsgList = new List<Messages>() { new Messages() { MsgID = 1, Content = "aaa" }, new Messages() { MsgID = 2, Content = "bbb" }, new Messages() { MsgID = 3, Content = "ccc" }, new Messages() { MsgID = 4, Content = "ddd" }, new Messages() { MsgID = 5, Content = "eee" }};

            int [] sentMsgIDs = SentList.Select(v => v.MsgID).ToArray();
            List<Messages> result1 = MsgList.Where(o => !sentMsgIDs.Contains(o.MsgID)).ToList<Messages>();

Надеюсь, что это поможет.

Ответ 7

List<Car> cars = new List<Car>() {  new Car() { Name = "Ford", Year = 1892, Website = "www.ford.us" }, 
                                    new Car() { Name = "Jaguar", Year = 1892, Website = "www.jaguar.co.uk" }, 
                                    new Car() { Name = "Honda", Year = 1892, Website = "www.honda.jp"} };

List<Factory> factories = new List<Factory>() {     new Factory() { Name = "Ferrari", Website = "www.ferrari.it" }, 
                                                    new Factory() { Name = "Jaguar", Website = "www.jaguar.co.uk" }, 
                                                    new Factory() { Name = "BMW", Website = "www.bmw.de"} };

foreach (Car car in cars.Where(c => !factories.Any(f => f.Name == c.Name))) {
    lblDebug.Text += car.Name;
}

Ответ 8

В качестве метода расширения

public static IEnumerable<TSource> AreNotEqual<TSource, TKey, TTarget>(this IEnumerable<TSource> source, Func<TSource, TKey> sourceKeySelector, IEnumerable<TTarget> target, Func<TTarget, TKey> targetKeySelector) 
{
    var targetValues = new HashSet<TKey>(target.Select(targetKeySelector));

    return source.Where(sourceValue => targetValues.Contains(sourceKeySelector(sourceValue)) == false);
}

например.

public class Customer
{
    public int CustomerId { get; set; }
}

public class OtherCustomer
{
    public int Id { get; set; }
}


var customers = new List<Customer>()
{
    new Customer() { CustomerId = 1 },
    new Customer() { CustomerId = 2 }
};

var others = new List<OtherCustomer>()
{
    new OtherCustomer() { Id = 2 },
    new OtherCustomer() { Id = 3 }
};

var result = customers.AreNotEqual(customer => customer.CustomerId, others, other => other.Id).ToList();

Debug.Assert(result.Count == 1);
Debug.Assert(result[0].CustomerId == 1);

Ответ 9

List<Person> persons1 = new List<Person>
           {
                    new Person {Id = 1, Name = "Person 1"},
                    new Person {Id = 2, Name = "Person 2"},
                    new Person {Id = 3, Name = "Person 3"},
                    new Person {Id = 4, Name = "Person 4"}
           };


        List<Person> persons2 = new List<Person>
           {
                    new Person {Id = 1, Name = "Person 1"},
                    new Person {Id = 2, Name = "Person 2"},
                    new Person {Id = 3, Name = "Person 3"},
                    new Person {Id = 4, Name = "Person 4"},
                    new Person {Id = 5, Name = "Person 5"},
                    new Person {Id = 6, Name = "Person 6"},
                    new Person {Id = 7, Name = "Person 7"}
           };
        var output = (from ps1 in persons1
                      from ps2 in persons2
                      where ps1.Id == ps2.Id
                      select ps2.Name).ToList();

Персональный класс

public class Person
{        
    public int Id { get; set; }       

    public string Name { get; set; }
}