首页 新闻 会员 周边 捐助

请教List求交集的Linq问题

2
悬赏园豆:20 [已解决问题] 解决于 2012-02-22 10:06

代码如下:

class Program
{
static void Main(string[] args)
{
List<A> aList = new List<A>()
{
new A(){ Id=1,Names=new List<string>(){"a","b","c"}},
new A(){ Id=2,Names=new List<string>(){"b","c","d"}},
new A(){ Id=3,Names=new List<string>(){"c","d","e"}},
new A(){ Id=4,Names=new List<string>(){"d","e","f"}},
new A(){ Id=5,Names=new List<string>(){"e","f","g"}}
};
List<string> test = new List<string>() { "b", "f" };

var val=//求aList中Names属性与test有交集的A集合

Console.Read();
}
}

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

public List<string> Names { get; set; }
}

请教代码中注释的部分的写法,也就是得出id为1、2、4、5的A的集合,谢谢,用linq写

乱世文章的主页 乱世文章 | 初学一级 | 园豆:147
提问于:2012-02-13 11:03
< >
分享
最佳答案
4
var val = aList.FindAll(a => a.Names.Any(test.Contains));
收获园豆:15
LCM | 大侠五级 |园豆:6876 | 2012-02-13 11:26

吹毛求疵一下, FindAll不是LINQ的方法 - - 

水牛刀刀 | 园豆:6350 (大侠五级) | 2012-02-13 13:44

@水牛刀刀: 多谢提醒。那把FindAll换成where不就可以了。

var val = aList.Where(a => a.Names.Any(test.Contains));



LCM | 园豆:6876 (大侠五级) | 2012-02-13 13:51

@LCM: :)

水牛刀刀 | 园豆:6350 (大侠五级) | 2012-02-13 13:54

@水牛刀刀: 不过我测了一下这三种的性能,你看下代码。

Stopwatch stw = new Stopwatch();
stw.Start();
for (int i = 0; i < 1000; i++)
{
var val = aList.FindAll(a => a.Names.Any(test.Contains));
}
stw.Stop();
Console.WriteLine(stw.ElapsedTicks);
//---------------------------------
stw.Reset();
stw.Start();
for (int i = 0; i < 1000; i++)
{
var val1 = aList.Where(a => a.Names.Any(test.Contains));
}
stw.Stop();
Console.WriteLine(stw.ElapsedTicks);
//---------------------------------
stw.Reset();
stw.Start();
for (int i = 0; i < 1000; i++)
{
var val2 = aList.Where(a => a.Names.Intersect(test, StringComparer.OrdinalIgnoreCase).Any()).ToList();
}
stw.Stop();
Console.WriteLine(stw.ElapsedTicks);

结果如下:

5539254
537250
15661632



LCM | 园豆:6876 (大侠五级) | 2012-02-13 13:59

@LCM: 第二种,你ToList一下,应该跟第一种差不多的。第三种多遍历了数据,所以会最慢。

水牛刀刀 | 园豆:6350 (大侠五级) | 2012-02-13 14:25

@水牛刀刀: 嗯

LCM | 园豆:6876 (大侠五级) | 2012-02-13 14:32

@LCM:

如果不区分大小写,前两种方法可以实现吗?

乱世文章 | 园豆:147 (初学一级) | 2012-02-13 15:05

@乱世文章: 

var val1 = aList.Where(a => a.Names.Any(n => test.Any(t => t.Equals(n, StringComparison.InvariantCultureIgnoreCase)));


水牛刀刀 | 园豆:6350 (大侠五级) | 2012-02-13 17:01

@水牛刀刀: 正解

LCM | 园豆:6876 (大侠五级) | 2012-02-13 17:03
其他回答(2)
1
var val = aList.Where(a => a.Names.Intersect(test, StringComparer.OrdinalIgnoreCase).Any()).ToList();
收获园豆:5
artwl | 园豆:16736 (专家六级) | 2012-02-13 13:42

这种写法会遍历test,而不是像楼上的那种,找到就会停止了。

支持(0) 反对(0) 水牛刀刀 | 园豆:6350 (大侠五级) | 2012-02-13 13:53
1
public class newArray<K> implements List<K>{
    
    private Object[] a =  new Object[8];
    private int at = 0;
    
    private void setSize(Object[] a,int index){
        if( index > a.length-1 ){
            int times = (int) Math.ceil((float)index/(float)(a.length-1));
            int length = (int)times *(a.length);
            Object[] b = new Object[length];
            for(int i = 0 ; i < a.length ; i++){
                    b[i] = (K)a[i];
            }    
            this.a = b;
        }
    }
    
    public String toString(){
        StringBuffer Str = new StringBuffer().append("[");
        boolean isFirst = true;
        for(int i = 0 ; i < at ; i++ ){
            if(isFirst){
                isFirst = false;
            }else{
                Str.append(" , ");
            }
            Str.append((K)a[i]);
        }
        Str.append("]");
        return Str.toString();
    }
    
    @Override
    public boolean add(K e) {
        setSize(a,at);
        a[at] = e ;
        at++;
        return false;
    }

    @Override
    public void add(int index, K element) {
        if( at > index ){
            a[index] = element;
        }else{
            throw new IndexOutOfBoundsException("Index:"+index+", Size: "+at);
        }
    }

    @Override
    public boolean addAll(Collection<? extends K> c) {
        Object[] o = c.toArray();// TODO Auto-generated method stub
        for(int i = 0 ; i < o.length ; i++ ){
            add((K)o[i]);
        }
        return false;
    }

    @Override
    public boolean addAll(int index, Collection<? extends K> c) {
        if( (at-1) < index ){
            throw new IndexOutOfBoundsException("Index:"+index+", Size: "+at);
        }
        Object[] o = c.toArray();// TODO Auto-generated method stub
        this.at = index;
        for(int i = 0 ; i < o.length ; i++ ){
            add((K)o[i]);
        }
        return false;
    }

    @Override
    public void clear() {
        this.a = new Object[8];
        this.at = 0;
    }

    
    
    @Override
    public boolean contains(Object o) {
        if(o != null){
            for(int i = 0 ; i < at ; i++ ){
                if( ((K)o).equals((K)a[i]) || (K)o == (K)a[i] ) return true ;
            }
        }else{
            for(int i = 0 ; i < at ; i++ ){
                if(a[i] == null) return true ;
            }
        }
        return false;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        Object[] o = c.toArray();// TODO Auto-generated method stub
        for(int i = 0 ; i < o.length ; i++ ){
            if(!contains(o[i])) return false;
        }
        return true;
    }

    @Override
    public K get(int index) {
        if( at > index ){
            return (K)a[index];
        }else{
            throw new IndexOutOfBoundsException("Index:"+index+", Size: "+at);
        }
    }

    @Override
    public int indexOf(Object o) {
        int j = -1;
        if(o != null){
            for(int i = 0 ; i < at ; i++ ){
                if(((K)o).equals((K)a[i])) return i ;
            }
        }else{
            for(int i = 0 ; i < at ; i++ ){
                if(a[i] == null) return i ;
            }
        }
        return -1;
    }
    
    @Override
    public int lastIndexOf(Object o) {
        int j = -1;
        if(o != null){
            for(int i = (at-1) ; i > -1 ; i-- ){
                if(((K)o).equals((K)a[i])) return i ;
            }
        }else{
            for(int i = (at-1) ; i > -1 ; i-- ){
                if(a[i] == null) return i ;
            }
        }
        return -1;
    }
    
    @Override
    public boolean isEmpty() {
        return (at==0);
    }

    @Override
    public Iterator<K> iterator() {
        Iterator<K> i = new Iterator<K>() {
            private int now = 0;
            @Override
            public boolean hasNext() {
                return ( now < at );
            }

            @Override
            public K next() {
                K k = (K)a[now];
                now++;
                return k;
            }

            @Override
            public void remove() {
                
            }
        };
        
        return i;
    }

    

    @Override
    public ListIterator<K> listIterator() {
        ListIterator<K> i = new ListIterator<K>() {
            
            private int now = 0;
            @Override
            public void add(K e) {
                
            }

            @Override
            public boolean hasNext() {
                return ( now < at );
            }

            @Override
            public boolean hasPrevious() {
                return (now > 0);
            }

            @Override
            public K next() {
                K k = (K)a[now];
                now++;
                return k;
            }

            @Override
            public int nextIndex() {
                if(now < ( at - 1 ) ){
                    return now+1;
                }else{
                    return -1;
                }
            }

            @Override
            public K previous() {
                if(now > 0 ){
                    return (K)a[now-1];
                }else{
                    throw new IndexOutOfBoundsException("iterator is at the begainest");
                }
            }

            @Override
            public int previousIndex() {
                if(now > 0 ){
                    return now-1;
                }else{
                    return -1;
                }
            }

            @Override
            public void remove() {
                // TODO Auto-generated method stub
                
            }

            @Override
            public void set(K e) {
                // TODO Auto-generated method stub
                
            }
        };
        return null;
    }

    @Override
    public ListIterator<K> listIterator(int index) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean remove(Object o) {
        int i = indexOf(o);
        while(i != -1){
            remove(i);
            i = indexOf(o);
        };
        return false;
    }

    @Override
    public K remove(int index) {
        for(int j = index ; j < at ; j++ ){
            a[j] = a[j+1];
        }
        at--;
        return null;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        Iterator<K> i = (Iterator<K>) c.iterator();
        while(i.hasNext()){
            remove((K)i.next());
        }
        return false;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return false;
    }

    @Override
    public K set(int index, K element) {
        add( index,  element);
        return null;
    }

    @Override
    public int size() {
        return at;
    }

    @Override
    public List<K> subList(int fromIndex, int toIndex) {
        List<K> result = new newArray<K>();
        if( toIndex < fromIndex ){
            throw new IndexOutOfBoundsException("fromIndex:"+fromIndex+", toIndex: "+toIndex);
        }
        if( (at-1) < fromIndex ){
            throw new IndexOutOfBoundsException("fromIndex:"+fromIndex+", Size: "+at);
        }
        if(toIndex > at) toIndex = at;
        for(int i = fromIndex ; i < toIndex ; i++){
            result.add((K)a[i]);
        }
        return result;
    }

    @Override
    public Object[] toArray() {
        Object[] arr = new Object[at];
        for(int i = 0 ; i < at ; i++){
            arr[i] = a[i];
        }
        return arr;
    }

    @Override
    public <T> T[] toArray(T[] a) {
        a = (T[]) toArray();
        return null;
    }

}
无泪的寂寞 | 园豆:202 (菜鸟二级) | 2013-08-30 15:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册