如何比较和获取List< T>中的项目根据对象类型 [英] How to compare and get items in List<T> base on object type

查看:123
本文介绍了如何比较和获取List< T>中的项目根据对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有2个不同的列表1,其中包含我认为是必需项的项目,而另一个是用户提供的.我需要对照我的列表检查传递给我的所有列表,并获取用户未能包括的所有项目.该检查基于物料类别类型.有什么方法可以做到,而不必在列表上循环查看并一一比较?

Hi guys I have 2 different List 1 that holds items that I see as a requirements and the other one is user provided. I need to check all the List passed on to me against my List and get all items that the user failed to include. The checking is based on item class type. Is there any way I can do this without looping on my list and comparing one by one?

顺便说一句,我仍在使用.net 2.0,但尚无Lambda表达式.

By the way I'm still using .net 2.0 which no Lambda expression yet.

感谢您的回答.我想我坚持使用它,但是找到了一种非常不错的方法来使其比旧方法更好.

EDIT 2: Thanks for the answer. I guess I'm stuck on looping with it but found some pretty nice way to make it far better than the old one does.

推荐答案

不确定我是否完全了解您的要求,但我认为有一个类型列表,然后是一个对象列表,您想查看对象列表中缺少哪些类型.那是对的吗?如果是这样,您可能正在搜索类似

Not sure I'm in full understanding of what you're asking, but I think you have a list of types and then a list of objects and you want to see what types are missing in the list of objects. Is that correct? If so, you may be searching for something like this

List<Type> types = new List<Type>() { typeof(int), typeof(double), typeof(float) };
List<object> objects = new List<object>() { 1, 2, 3, 2d, 4d };

var missingTypes = types.Except(objects.Select(obj => obj.GetType()));

在这种情况下,将导致只包含float类型的序列.通过使用LINQ,您可以循环播放,但是可以将其抽象化.

Which, in this case, would result in a sequence that simply contains the type for float. By using LINQ, you are looping but it is abstracted away.

编辑:在.NET 2.0中,您可以执行以下操作来获取丢失的类型.您仍在循环播放,但这还不错.您也许可以写得更好,并且当然可以在3.5+(甚至没有LINQ)中也可以写得更好,但是它应该可以帮助您入门.

In .NET 2.0, you can do something like the following to get your missing types. You're still looping, but it's not too bad. You might be able to write this better, and you could certainly write it better in 3.5+ (even without LINQ), but it should get you started.

static IEnumerable<Type> GetMissingTypes(IEnumerable<Type> types, List<object> objects)
{
    List<Type> existingTypes = objects.ConvertAll(delegate(object obj) { return obj.GetType(); });
    foreach (Type type in types)
    {
        if (!existingTypes.Contains(type))
            yield return type;
    }
}

// ...

List<Type> types = new List<Type>() { typeof(int), typeof(double), typeof(float) };
List<object> objects = new List<object>() { 1, 2, 3, 2d, 4d };
IEnumerable<Type> missingTypes = GetMissingTypes(types, objects);

这篇关于如何比较和获取List&lt; T&gt;中的项目根据对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆